How To Show Only Filenames with grep on Linux

Bash Shell

grep is a Linux utility for searching text files. By default, it will print out the results of the search, but it can also be used to match and print file names that contain the search result, which can be useful when connecting it with other scripts.

Using grep To Print Filenames

grep is commonly used alongside other commands in bash scripts as a general text search utility. However, by default, it doesn’t print anything about the filenames, which you might need if you’re passing the output to another utility.

If you want a list of the files that match, you can use grep with the -l flag, which will list the filenames instead of the match:

grep -l foo ./*

This is similar to the -H flag, which will output a response containing the filename followed by the matched line. However, with -l, it will only print the filename, giving you a list of files that contain the search string.

You can also use an uppercase -L flag to do the reverse: print all the files that don’t contain the matched string.

grep -L baz ./*

Trimming The File Path

By default, the -l flag will print files with a relative file path pre-appended. If you just want the actual file name, you can trim the file path using the basename utility. This will require the input to be passed in through xargs, but works pretty well:

grep -l foo ./* | xargs -L 1 basename

Keep in mind that grep -r will search recursively, and if you use that with basename, the response may contain files with trimmed paths that are not in the current directly.

Using grep With The find Command

grep also works well with the extra searching utility of the find command. For example, you can use it with the find command to search every text file in a directory and easily run a grep search:

find . -iname "*txt" -exec grep foo {} ;

Or use it with the -l flag to list filenames:

find . -iname "*txt" -exec grep -lH foo {} ;

Source link

Leave a Reply

Your email address will not be published.