Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display filename before matching line

Tags:

grep

unix

How can I get grep to display the filename before the matching lines in its output?

like image 405
Vivek Avatar asked Mar 15 '13 12:03

Vivek


People also ask

How do you display the filename in Unix?

ls - displays file names. ls –l - displays file names with permissions, site, owner, etc. man commandname - on-line help for the command specified (Use for complete description).

How do you grep for filename recursively?

If you are using GNU grep, then you can use the following: grep -ir --include "*. cpp" "xyz" . The command above says to search recursively starting in current directory ignoring case on the pattern and to only search in files that match the glob pattern "*.

How do you grep two lines before and after?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.


1 Answers

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 
like image 99
Scrutinizer Avatar answered Oct 23 '22 13:10

Scrutinizer