The ultimate grep

Every now and then I find myself in a situation where I have to search for a particular string from a set of files, and every time I have to remind myself again by googling. Well not anymore because I decided to write this down.

## The ultimate grep
# -r Recusive, -n Display line number, -w Whole words, -i Ignore case, 
#  -I Ignore binary
$ grep -rnwiI /path/to/dir -e "String to Search"

So in my current example, I work on Nagios and I want to find the file containing that check_snmp command i would type:

$ grep -rnw '/etc/nagios/objects/' -e 'check_snmp'
/etc/nagios/objects/commands.cfg:147:# 'check_snmp' command definition
/etc/nagios/objects/commands.cfg:149:        command_name    check_snmp

From here we can basically see the file where check_snmp is defined along with the line number of that file.

By extending the command with --include or --exclude parameter we can adjust command to also search for files with particular extension. The bellow command will check only .cfg or .conf files.

$ grep --include=\*.{cfg,conf} -rnw '/etc/nagios/objects/' -e 'check_snmp'
$ grep --exclue=\*.0 -rnw '/etc/nagios/objects/' -e 'check_snmp'

And as always, remember to RTDM!

$ man grep