Display filename before matching line
Solution 1:
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
Solution 2:
If you have the options -H
and -n
available (man grep
is your friend):
$ cat file
foo
bar
foobar
$ grep -H foo file
file:foo
file:foobar
$ grep -Hn foo file
file:1:foo
file: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
Solution 3:
No trick necessary.
grep --with-filename 'pattern' file
With line numbers:
grep -n --with-filename 'pattern' file