How Do I Use grep to Show Only Filenames on Linux?

Grep is the built-in Linux command used for searching the matching pattern in a file and directory.

It is mostly used by the system administrator to search the occurrences of a pattern in code and log files. In addition, it also helps to display the file name whose text matches the specified regular expression as the input. 

This guide describes how can the user show just filenames on Linux:

  • Using the “grep” Command with  “-l” Argument
  • Using the “grep” Command with the “find” Utility 

Method 1: Using the “grep” Command with  “-l” Argument

The “grep” command supports the “-l(files-with-matches)” flag to print the file name whose content matches the specified pattern or string. It searches the specified pattern from the system and displays just the filenames that exactly match the mentioned input(string/pattern).

Execute the grep command followed by the “-r(recursively)” and the “-l” flags to show the filenames whose text matches with the string “first”:

$ grep -rl "first"

The output shows the “File1.txt” and “File2.txt” after the recursive search from the “Downloads” directory.

Method 2: Using the “grep” Command with the “find” Utility. 

The grep” command is always used with the other command line utility in bash in the form of the search tool. Here it is used with the “find” command to perform the search operation on its output.

The “find” command supports the “exec” flag to execute the other command line utilities in this format:

$ find . -name "*.txt" -exec grep -l "file" {} \;

The command description is stated here:

  • find: Searches for the specfied file.
  • dot(.): Represents the present working directory.
  • name: Identifies the anime of the searched file
  • *.txt: Shows all(*) the files having “.txt” extension.
  • -exec: Allows the execution of the “grep -l” command on the result of the find command.
  • {}: Shows the placeholder that takes the file name given by the find command to execute the “grep -l” command.
  • \; Acts as a delimiter that identifies the end of the command.

The output shows that the “./File2.txt” filename contains the matches string “first”.


Linux’s “grep” command supports the “-l(files-with-matches)” flag to show just the filenames. It matches the mentioned string/pattern from the system files and prints their names as standard output. In addition, the grep command can also be executed with “find” to print the file names that are found in the result of its search.

This post has provided a detailed view of how can grep command can be used to show just filenames on Linux.