How to use grep to only show filenames in Linux

Overview

In Linux/Unix, the grep command is a command-line tool used to search for a string in a file.

Syntax

grep <OPTIONS> [pattern] [files...]

The command has several options that are required for different purposes. One such option is -l or --files-with-matches.

When -l or --files-with-matches is enabled, only the names of files containing selected lines are written to standard output. The path names are listed once per file searched.

main.sh
file2.txt
file1.txt
educative
edpresso
hello

In the above code widget, we create two files called file1.txt and file2.txt with some text in them. Next, we search for the pattern hell* in the present working directory in all the text files only.

The output prints the filenames with the text matching the pattern. In order to get only filenames, we can enable the -l or the --files-with-matches flag.

Example

main.sh
file2.txt
file1.txt
educative
edpresso
hello

Free Resources