Thursday, 1 March 2012

Grep Command Examples

grep [options] PATTERN [FILE...]

The grep command basically searches though a file for lines which match the given pattern, for example:

grep apple fruit.txt

this will output all lines which contain the word apple, its as easy as that!
You could also specify a search in more then one file with the '*' wildcard

grep apple *.txt

like all good commands grep lets you use regular expressions such as the following:

grep ^a fruit.txt

the above line will return all lines which begin with the letter a.

Once you get the hang of grep you can do some pretty cool things, heres a command which I use a lot (provided by Sean, he know's who he is), it looks
complicated but I'll break it down:

grep --color=always -niC number "string" filename | less -R

--color=always this colours the pattern to make it jump out at you when searching
-niC number 
        'n' -  would be the line number, this isn't always needed so it can be removed.
        'i' - is to match both upper and lower-case
        'C number'  - is the number of lines surrounding the matches you want to show, the                       alternative is A and B which is to show lines before or after the match
"string" - The pattern, but then you already knew that ;)

file name is the file you are searching, you can use the '*' wildcard as mentioned above or you can type another file name next to it which will also work

| less -R
this is the pipe that lets you scroll down the output of the search, the -R is the necessary command to let the colour work with the scrolling
basically this makes it easier to read.

you can also save the output as a .txt file by using | tee output.txt and appending it to the end of the grep command, the cool thing  is that the colour stays in the output.txt!

There are loads of useful switches to use with grep try 'man grep' in the console

No comments:

Post a Comment