Thursday, February 24, 2011

5 useful Grep options that you must know

Grep is a very handy utility for searching for a pattern in files. While it has many options, every grep user should at-least know the following five options


-R, -r, --recursive

This option makes grep search all the files in the specified directory and its sub-directories, recursively. This specifically comes in handy for programmers when they are looking for the declaration or all uses of some variable/function/anything in the source tree.
So, for example if you want to search the current directory for all files containing the word "foo" then you can use:
grep -r foo .


-n, --line-number

This option makes grep to prefix the ouput with the line number of each matched line withing its input file. This makes it easier to make changes as you know the line number, so just open the file, go to the specific line and make the required changes.



-I

This option makes grep ignore binary files i.e binary files are not searched. This option is again very helpful for programmers who only want to search in the source files.



-A NUM, --after-context=NUM

This option prints NUM lines following the matched line from the input file. For example if you want the output to contain the matched line and 2 lines after it then you can use:
grep -A2 <PATTERN> <FILES>


-B NUM, --before-context=NUM

This option prints NUM lines before the matched line from the input file. So if you want the output to contain the matched line and 2 lines before it then you use
grep -B2 <PATTERN> <FILES>


No comments: