Thursday, February 4, 2016

Linux | How to search for a particular string in multiple files

Every now and then I find myself into 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.

As the old proverb says: "The fool remembers, the smart writes down."

That is why I decided to write this down, so that I can come back and find it again.

# grep -rnw '/path/to/somewhere/' -e "pattern"

Here -r or -R is recursive, -n is line number and -w stands match the whole word. We can also add -l (lower-case L) to just give the file name of matching files.

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'

Which will produce the output:

/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.

Extending the command with --include or --exclude parameter we can create neatly commands 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:


# man grep

No comments:

Post a Comment