Thursday, 1 March 2012
Grep Command Examples
grep [options] PATTERN [FILE...]
The grep command basicaly 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
this colours the pattern to make it jump out at you when searching
-niCn would be the line number, this isnt always needed so it can be removed.
'i' is to match both upper and lowercase
'C number' is the number of lines surrounding the matchs you want to show, the alternative is A and B which is to show lines before or after the match
"string" is the pattern, but then you already knew that ;)
filename 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 color work with the scrolling
basiccaly this makes it easier to read.
you can also save the ouput 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 color stays in the output.txt!
There are loads of useful switches to use with grep try 'man grep' in the console