Beginner’s guide to Linux commands – grep

grep is a great tool that all nix administrators use in their day to day work. Let see some interesting options available to it.

Searching a string

That is the basic usage of this tool.

Case insensitive search

grep has -i option for case insensitive search.

Search full word, not substring

If you are looking for word Ubu instead of Ubuntu, then use -w option.

Display lines before, after and around the matched line.

Grep has -A option to show lines after match, -B to show lines before match and -C for showing lines around matched line.

Following command will show 2 lines after the matched line.

To get 2 lines before matched line, try :

To display one line above and after matched line, use following command.

Recursive search

grep has -r or -R option to search a string in all files under the folder.

To suppress inclusion of filename in search result, use -h option.

Invert matching

Use -v option to show all unmatched lines.

Counting matched and unmatched lines

To get count of all matched lines.

For getting count of all unmatched lines.

Show matched line number

Show just name of the file with matched string

grep option -l will show only name of the file.

Match entire line

grep’s -x option matches entire line and not just word or its substring.

Only matching and quiet

grep’s -o will output only matched string and -q will suppress all output and only return match status code.

Extended and Fixed options

Grep options -E matches extended regex patterns and -F matches fixed strings separated by newline.

Following extended regex matches two words with space between them.

To match more than one pattern.

Which is same as :

-F considers everything as fixed string, so wild cards and other patterns won’t work.

Exclude or include files and directories to search

Grep provides --exclude= and --exclude-dir= to exclude file and directory from search and --include= to search only particular files.

Few other interesting grep examples

Suppress all error messages using -s.

Find all files under the current directory with strings Ubuntu and Centos.

Thats all about grep for now.