0

Here is my current code and I also prefer to show matched file name as well (if the content of the file matched grep), any solutions are appreciated.

for file in *.py;
do grep -n --color 'main' $file;
done

BTW, I am using Linux/OS X.

thanks in advance, Lin

Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • possible duplicate of [How can I use grep to show just filenames (no in-line matches) on linux?](http://stackoverflow.com/questions/6637882/how-can-i-use-grep-to-show-just-filenames-no-in-line-matches-on-linux) – msw Aug 27 '15 at 01:01

2 Answers2

6

If you're using GNU grep, you can use the -H or --with-filename option to force it to display the filename even when there's only one file argument.

for file in *.py; do
    grep -H -n --color 'main' $file
done

Both Linux and OS X use GNU grep, so it should work in both environments.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

I'm sure this has been on here before, but you just need to give it a second file name

for file in *.py; 
do grep -n --color 'main' $file /dev/null;
done
Dave Satch
  • 1,161
  • 6
  • 12
  • your solution works for me and want to learn more why adding /dev/null works and what do you mean "give it a second file name"? – Lin Ma Aug 27 '15 at 00:26
  • 1
    with grep, you can give it multiple files to search at once. For example, "grep filea fileb filec". When you do so, the output will tell you which file contains the match. In this case, we have 'tricked' it. /dev/null will never contain the match, but because we have given two file names to grep, it will show you which file has matched. – Dave Satch Aug 27 '15 at 00:28
  • smart. You mean if we use grep on only one file, grep never shows file name? – Lin Ma Aug 27 '15 at 00:32