How to grep Search for Filenames Instead of Content in Linux

Estimated read time 3 min read


Bash Shell

grep is a Linux tool usually used for searching text files for specific content. However, it’s often useful to search directories for file names instead of file contents, and this can be done with grep and other Linux command line utilities

Using find Instead of grep

The grep utility essentially takes string input from files or standard input and uses patterns or Regex to search through it and print matching lines.

You can technically use grep by itself to search for file names instead of content, but it’s only because Linux allows wildcards in filename inputs. However, you can just as easily use ls to list files this way, or use wildcards in any other command, and it isn’t a real solution for searching filenames like how grep searches content.

grep "" ./file* -l

The real solution is to use the find utility, which can search through sub-directories and provides the most resilient way to search for files as it interacts directly with the filesystem. This is the most commonly used utility for searching through directories, and it has a lot of options—including pattern matching and Regex support.

The most basic usage is to use find on its own to print out a list of files, including subdirectories, and feed that input to grep. If you already have scripts using grep, it will be pretty easy to convert them to matching this way.

find | grep "file"

You can also use patterns directly with find, eliminating the need for grep. Use -iname with an input.

find . -iname 'file_*.txt'

Unlike grep however, the find command is a little more strict—you need to use single or double quotes to escape the search string, and you need to use wildcards to match the entire string. Simply finding a substring in the name is not possible without using wildcards to match the rest of the name.

Using Regular Expressions (Regex) With find

You can also use regular expressions with find, which allows much more advanced matching:

find . -regex './file.*'

This regex will match all files in the current directory starting with “file.” However, it’s important to be aware that this works differently than -iname; the input includes the full directory path, and must use ./ to escape the relative path, ./.

This command shown here is excluding the ./subdirectory/ folder, because it doesn’t start with “file”. To fix this, you must match everything leading up to the final forward slash with .*/:

find . -regex '.*/file.*'

Regular expressions are highly complicated, but very powerful. If you’d like to learn more, you can read our guide on how they work.

RELATED: How Do You Actually Use Regex?





Source link

You May Also Like

More From Author