Display filename before matching line Display filename before matching line unix unix

Display filename before matching line


Try this little trick to coax grep into thinking it is dealing with multiple files, so that it displays the filename:

grep 'pattern' file /dev/null

To also get the line number:

grep -n 'pattern' file /dev/null


If you have the options -H and -n available (man grep is your friend):

$ cat filefoobarfoobar$ grep -H foo filefile:foofile:foobar$ grep -Hn foo filefile:1:foofile:3:foobar

Options:

-H, --with-filename

Print the file name for each match. This is the default when there is more than one file to search.

-n, --line-number

Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.)

-H is a GNU extension, but -n is specified by POSIX


No trick necessary.

grep --with-filename 'pattern' file

With line numbers:

grep -n --with-filename 'pattern' file