Monday, April 25, 2011

Filenames and linenumbers for the matches of cat and grep

My code

$  *.php | grep google

How can I print the filenames and linenumbers next to each match?

From stackoverflow
  • grep google *.php
    

    if you want to span many directories:

    find . -name \*.php -print0 | xargs -0 grep -n -H google
    

    (as explained in comments, -H is useful if xargs comes up with only one remaining file)

    Masi : Does the latter code find subdirectories or master directories?
    Jonathan Leffler : You need the name because you may not know which file it was - especially if it is bad break that xargs batched things up and had a single file left over.
    Michael Trausch : Don't forget that you should use -print0 to find and -0 to xargs if you are working in a directory tree that has names with things like embedded whitespace in them.
    cadrian : @Jonathan & Michael: yes, you are right. I gave the most common case though. @Masi: subdirectories
    DevSolar : Your first line doesn't print filenames and numbers, the second recurses (which Masi didn't imply). "find . -maxdepth 1 -name \*.php -print0 | xargs -0 grep -nH google" would fit the bill.
  • Use "man grep" to see other features.

    for i in $(ls *.php); do  grep -n --with-filename "google" $i; done;
    
    Alnitak : that won't work - the input file is "stdin" when the command is written this way
    J.J. : You right. Changed the code to work.
  • You shouldn't be doing

    $ *.php | grep
    

    That means "run the first PHP program, with the name of the rest wildcarded as parameters, and then run grep on the output".

    It should be:

    $ grep -n -H "google" *.php
    

    The -n flag tells it to do line numbers, and the -H flag tells it to display the filename even if there's only file. Grep will default to showing the filenames if there are multiple files being searched, but you probably want to make sure the output is consistent regardless of how many matching files there are.

  • find . -name "*.php" -print | xargs grep -n "searchstring"
    
  • find ./*.php -exec grep -l 'google' {} \;

    Jonathan Leffler : That gets the file names, but not the line numbers, doesn't it?
  • grep -RH "google" *.php
    
  • Please take a look at ack at http://betterthangrep.com. The equivalent in ack of what you're trying is:

    ack google --php
    

0 comments:

Post a Comment