Sometimes during general system administration you find yourself need to do a string search on files. This could be to locate a css that contains a specific class name and property, or you need to look for specific function call within a system files.

The way to achieve this is to you the grep command with a few options.

Find all occurrences of a string with files and subdirectories:

$ grep -rl 'search term' path/to/files

Arguments and descriptions:
-r option is used to traverse also all sub-directories of /path.
-l option is used to only print filenames of matching files.

The same as above, but with line numbers printed:

$ grep -Hrn 'search term' path/to/files

Arguments and descriptions:
-H causes the filename to be printed (implied when multiple files are searched)
-r does a recursive search
-n causes the line number to be printed
path/to/files can be . to search in the current directory

Further options that I find very useful:
-I ignore binary files (complement: -a treat all files as text)
-F treat search term as a literal, not a regular expression
-i do a case-insensitive search

Share This