Technology

How to Use grep to Display Filenames & Line Numbers Before Matching Lines

grep is a Linux utility commonly used for searching file contents, or any input passed to it. When searching through multiple files, it’s useful to display the filename and line numbers, especially when using it to automate in shells scripts.

Displaying Filenames With grep

By default, if you pass multiple files to grep, it will display filename: before the matching line for clarity. You can actually turn this behavior off with the -h flag, which will never display filenames:

However, if you only pass one file into grep, it won’t display the filenames by default. This can be a problem when automating with shell scripts, as you might not know how many files are in a directory, and it may break automation relying on the file name being there.

The simple fix is to use the uppercase -H flag, which does the opposite of -h and will always turn on the filenames no matter what, even with only one file passed as input.

grep -H "foo" file

The -H flag has another unexpected but useful effect—when paired with input from stdin, such as Unix pipes, it will print (standard input): in place of the filename.

Displaying Line Numbers With grep

You can also use it in conjunction with the -n flag to get the line number:

grep -Hn "foo"

A POSIX Compliant Hack

The -H flag in grep isn’t POSIX compliant and isn’t available some more obscure Unix-based operating systems. Luckily, there’s a hack you can use, by passing /dev/null as a fake second file input to grep, which tricks it into thinking there are multiple files:



File source

Tags
Show More

Related Articles

Back to top button
Close