Thursday, January 22, 2009

Using grep for dummies

There are some ppl who ask me why linux is so powerful, well for me i would say its most power becos you can do almost most everything from the command line ,one unevitable point being that it save a lot of memory with not need of having any fashionable uis. One of the very important command which i think is the gerp command.
Grep : grep is a very simple command used to search text either from a file or from any source.we'll get to see what an other source in the later part.
Here is list some simple usage of grep with examples.
1.Simple search. The simplest way to use grep is as follows.
$grep

Example:
Here we are trying to search the word 'cat' in the file animals.txt
knoppix@Knoppix:~$ grep cat animals.txtcat
There is a black cat here.
wild cat is in the jungle

we'll few ppl also use the same command with the search term in the single quotes '', the result would be the same if you are searching for a single word. you should be using single quotes in case you are searchig for a set of words in a file eg 'black cat'

knoppix@Knoppix:~$ grep 'black cat' animals.txt
There is a black cat here.

To make the search insensitve use the -i option .
knoppix@Knoppix:~$ grep -i 'white cat' animals.txt
There is a white Cat here.

2.Using regex.
find the lines containg startin with 'cat'
knoppix@Knoppix:~$ grep '^cat' animals.txt
cat's tail
cat was in the box

Find the lines ending with cat
knoppix@Knoppix:~$ grep 'cat$' animals.txt
dirty cat
black cat
find the lines containing the only the word cat i donno.. :) ,
you find out and tell me.

3.search for lines containing characters
knoppix@Knoppix:~$ grep '[0-9]' animals.txt
cat no. 420

search for lines containing characters
knoppix@Knoppix:~$ grep '[a-z]' animals.txt
a big cat
dirty cat
cat no.420

4.grep is mostly used in conjuction with other commands, here are some examples.
ps aux grep java
this will find all the programs which have java in their name

other usages can be
ps aux grep -i java
ps aux grep -i java wc -l returns the no of lines
piping the out put again to grep to further filter data
ps aux grep -i java grep -v jdev
find all programs containing java and not jdev

5.Invert search criteria
grep -v 'cat' animals.txt
get more lines above and below the seached line
grep -C 2 'cat' animals.txt
white dog
black cat
big wolf

No comments: