1

Task:
1) find a string 'decor' inside files in a directory
2) get # of occurrence for decor for each file that has it

The first part of the problem is partially solved with find . -type f | grep -i decor *
But this doesn't seem grep for all files that are found from find but rather what's on top of current directory.
Do I have to use something other than * for grep to grep for files found from find?

what needs to be piped to so that it will display with a file name and the number of occurrences for decor for each file?

0

4 Answers 4

2

You can do:

find . -type f -exec grep -icH decor {} \; | grep -v :0\$

This will get the filename and count of each match and remove files with a count of 0 using the piped egrep

2
  • No problem! Note the edit however, without the colon it'll ignore any number ending in 0, so 10, 100 etc...
    – arco444
    Jan 14, 2014 at 14:28
  • Just for the fun of it, and way beyond the scope of this exercise, I issued a find2perl . -type f -exec grep -icH {} \; to see if I'm willing to add the grep -v :0\$ part. Looks doable, perhaps later during Jeopardy. Feb 2, 2014 at 0:56
2

"Files in a directory" does not usually mean "and iside subdirectories recursively". I would just use

grep -c decor *

If you need to search subdirectories, too, you can use find, but connect the commands differently: pipe just connects output of the first command to the input of the second. Grep does not expect list of files on its input, though.

find . -type f -exec grep -cH decor {} + | grep -v :0
0

You can use -exec option. find . -type f -exec grep decor {} \;

or use xargs find . -type f | xargs -i grep decor {}

1
  • -1: i) this breaks on filenames with white space and ii) neither of the solutions return the number of matches for decor which is what the OP asked for.
    – terdon
    Jan 14, 2014 at 15:31
0

TMTOWTDI - I like seeing the other variants, so here's mine as well:

$ find . -type f -exec egrep -li decor {} \;

$ perl -e '$c=0; while(<>){$c++ if /decor/;} continue {if(eof){print("$ARGV:$c\n"); close ARGV; $c=0;} }' *

Just because I felt like re-writing a Perl 1-liner that performs the same as an age old awk example taken from the pages of Kernighan and Pike.

2
  • TMTOWTDI - Sounds like something worth doing. Note the perl2find not so useful suggestion, above - just for fun. You already worked out my answer, with the same reference. Bravo! Feb 2, 2014 at 1:02
  • BTW - That while(<>){} continue {if(eof){close ARGV;} idiom is worth memorizing. Again, that Perl idiom is worthy of memorization. Feb 2, 2014 at 1:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .