29/11/2024

Tech Guru

Trusted Source Technology

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

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

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

grep is a Linux utility typically employed for seeking file contents, or any input passed to it. When browsing by means of various files, it is useful to display screen the filename and line numbers, primarily when employing it to automate in shells scripts.

Exhibiting Filenames With grep

By default, if you go many files to grep, it will show filename: before the matching line for clarity. You can actually transform this actions off with the -h flag, which will hardly ever display filenames:

Nonetheless, if you only pass a single file into grep, it will not exhibit the filenames by default. This can be a trouble when automating with shell scripts, as you could possibly not know how quite a few files are in a listing, and it may well crack automation relying on the file identify remaining there.

The easy deal with is to use the uppercase -H flag, which does the opposite of -h and will normally transform on the filenames no make a difference what, even with only one file handed as input.

grep -H "foo" file

The -H flag has another unanticipated but valuable effect—when paired with input from stdin, this sort of as Unix pipes, it will print (typical input): in place of the filename.

Exhibiting Line Numbers With grep

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

grep -Hn "foo"

A POSIX Compliant Hack

The -H flag in grep isn’t POSIX compliant and is not readily available some more obscure Unix-based working systems. The good news is, there is a hack you can use, by passing /dev/null as a fake second file input to grep, which tricks it into considering there are a number of documents: