How to grep search for filenames instead of content in Linux

0
382

[ad_1]

grep is a Linux tool that is generally used to search text files for specific content. However, it is often useful to search directories for file names rather than file contents, and this can be done with grep and other Linux command line utilities

Using find instead of grep

the grep The utility essentially takes string input from files or standard input and uses patterns or regular expressions to find and print matching lines.

Technically you can use grep by itself to search for filenames rather than content, but that’s only because Linux allows wildcards in filename entries. However, you can easily use ls list files like this, or use wildcards in any other command, and it’s not a real solution for searching filenames like grep search content.

grep "" ./file* -l

The real solution is to use the find utility, which can search through subdirectories and provides the most robust way to search for files as it interacts directly with the file system. This is the most widely used utility for searching directories and has many options, including pattern matching and Regex support.

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

find | grep "file"

You can also use patterns directly with findeliminating the need for grep. Use -iname with one input.

find . -iname 'file_*.txt'

Unlike grep However the find The command is a bit stricter: you must use single or double quotes to escape the search string, and you must use wildcards to match the entire string. It is simply not possible to find a substring in the name without using wildcards to match the rest of the name.

Using regular expressions (regex) with find

You can also use regular expressions with findwhich allows much more advanced matching:

find . -regex './file.*'

This regular expression will match all files in the current directory that start with “file”. However, it is important to note that this works differently than -iname; the input includes the full directory path and you should use ./ to escape the relative path, ./.

This command shown here excludes the ./subdirectory/ folder, because it doesn’t start with “file”. To fix this, you need to match everything leading to the trailing slash with .*/:

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

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

RELATED: How is Regex actually used?

[ad_2]