How can I use grep to show just filenames on Linux?
To show only the filenames containing matches (without printing the matching lines), use grep -l
. For instance:
grep -l "search_pattern" file1 file2 file3
This displays the names of files where "search_pattern"
occurs. If you want to search recursively in a directory, add -r
:
grep -rl "search_pattern" /path/to/search
-l
: Lists just the filenames with matches (one per line).-r
: Recursively searches all subdirectories.-i
: Makes the search case-insensitive (optional, if needed).
Additional Tips
-
Files That Don’t Contain the Pattern
If you need to list files that don’t match, use-L
instead of-l
:grep -rL "search_pattern" /path/to/search
-
Filtering by Filename
You can limit which files get searched by combining-r
with--include
:grep -rl --include="*.txt" "search_pattern" /path/to/search
-
Excluding Certain Directories
Skip directories likenode_modules
orvendor
by adding:grep -rl --exclude-dir="node_modules" "search_pattern" .
Further Learning
If you want to enhance your problem-solving skills and handle more advanced coding challenges (both on Linux and in other environments), check out these courses from DesignGurus.io:
-
Grokking Data Structures & Algorithms for Coding Interviews
Learn and master the core data structures and algorithms to improve your script and application performance. -
Grokking the Coding Interview: Patterns for Coding Questions
Discover the most common patterns in coding challenges, crucial for acing technical interviews and writing robust software.
By combining the power of Linux utilities like grep
with strong algorithmic knowledge, you’ll be well-prepared to tackle both everyday tasks and complex coding problems.