grep something with xargs and find

14,999

Solution 1

The -h option to grep suppress filenames from the output.

find /<path>/hp -iname '*.ppd' -print0 | xargs -0 grep -h "\*ModelName\:"

If your grep does not provide -h the use cat:

find /<path>/hp -iname '*.ppd' -print0 | xargs -0 cat | grep "\*ModelName\:"

Also, for your information, find provides the -exec option which would render xargs unnecessary had you wanted to pursue your second option:

find /<path>/hp -iname '*.ppd' -exec grep grep "\*ModelName\:" '{}' \;

Solution 2

No need for find:

grep -rh --include "*.ppd" "\*ModelName\:"

Solution 3

You can get rid of find altogether (in bash):

shopt -s globstar
grep -h "\*ModelName\:" /<path>/hp/**.[pP][pP][dD]

Might be a bit slower if you have a huge directory tree (which I doubt in your case).

  • Pro: only one process launched!
  • Con: the future improvement you mentioned might be more difficult to implement.

In this case, you'd better use:

find /<path>/hp -iname '*.ppd' -exec grep -h "\*ModelName\:" {} +

(observe the + at the end: only one grep will be launched).

Share:
14,999
likern
Author by

likern

Updated on June 04, 2022

Comments

  • likern
    likern almost 2 years

    bash guru ;) I'm trying to improve some string in bash which grep specific keyword's matches in specific files. It looks like that:

    find /<path>/hp -iname '*.ppd' -print0 | xargs -0 grep "\*ModelName\:"
    

    which works very fast for me! In 20 times faster than this one:

    find /<path>/hp -iname '*.ppd' -print0 | xargs -0 -I {} bash -c 'grep "\*ModelName\:" {}'
    

    But the problem is that in the first script I'm getting the following lines:

    /<path>/hp/hp-laserjet_m9040_mfp-ps.ppd:*ModelName: "HP LaserJet M9040 M9050 MFP"
    

    but desired result is just

    *ModelName: "HP LaserJet M9040 M9050 MFP"  
    

    (as in the second script). How can I achieve it?

    P.S.: I'm using find for flexibility and future improvements of the script.

  • kdubs
    kdubs over 11 years
    he was talking about speed also. the -exec will make it run slower, but it does solve the file name issue
  • likern
    likern over 11 years
    Which filename issues could be arised if I use find ... -print0 | xargs -0? Which problems find -exec solves which can't find ... -print0 | xargs -0? Maybe my code is error-prone?
  • likern
    likern over 11 years
    And yes, my first example was used find -exec which was dramatically slower... it took 23 seconds vs 0.3 seconds now. That's why I've decided to rewrite it.