Search This Blog

Sunday, November 29, 2026

print filenames containing a string

I used to use a combination of grep and awk commands to produce the list of files with a given string. For example, to get all the files in the "/etc" with a string "crux" I would run:

grep -sc crux /etc/**/*(.) | awk -F: '{if ($2!=0){print $1}}'

The key is to use the -c option, to count the number of lines with the string. The -s suppresses error messages. Then the output is passed to awk, which splits the line on "< b>:" and prints the first field, if the second one does not equal to 0. In the above example, I used the zsh globbing /etc/**/*(.) for recurse search of all files in the /etc directory.

But there is a simpler way.

grep -sl crux /etc/**/*(.)

The -l grep option suppresses normal output and prints only the file name containing the searched string.