I need to recursively find all files that contain a specific word and if the word exists in file I need to find out the number of lines in that file. I have been trying to use
grep but I have been not successful so far.
grep -Zlr "\<THE_WORD\>" * | xargs -0 wc -l
Options for grep:
-Z- end printed filenames with a zero/null byte to delimit them (helps with weird filenames, or those with spaces)
-l- list names of files, not the lines that match
-i- ignore case (optional, but probably useful to find ALL the variants)
And in the quotes, around
THE_WORD, I've used 'word delimiters' (
\>), which prevent 'HI' from being found in 'WHICH'. Useful, that.
Pipe the zero delimited list of filenames containing "THE_WORD" to
xargs, telling it to expect zero byte delimiters (
wc (word-count), showing line counts (
To answer your query in the comments, try this variation: (I've done some research!)
grep -oi "\<THE_WORD\>" /dev/null * | sort | uniq -c
-osays to output EVERY occurrence on the line, so if you have "blah blah THE_WORD blah THE_WORD blah blah", it'll output TWICE for that LINE, without this flag, grep would only output ONCE for this line.
-imatch upper & lowercase variations (ie, The_Word, the_word, etc)
\<must be a start of a word, thus 'HI' is NOT found in 'WHICH'.
- `>' must end on end of a word, again preventing 'HI' being found in 'WHICH'
/dev/nulla dummy filename to force grep to ALWAYS output filenames, even if you only search one file. This CAN be forced by using the
-Hoption for grep, but I find this just as easy and more descriptive since
-Hcould be rated as 'little-known-magic'
pipe all that to sort (which, uh.... sorts...)
pipe the sorted list to uniq, with
-cto count each occurrence in the sorted list
File example.c contains: (*H)->segments=realloc((*H)->segments,sizeof(segment_t*)*((*H)->segment_count+1)); xenon-lornix:~/projects/emma> grep -oi "\<H\>" /dev/null *.c | sort | uniq -c 3 example.c:H
Thus returning a list of a count (3), where (example.c), and what (H)!! Voila!! Yaaayy!!
Another, with same file contents:
xenon-lornix:~/projects/emma> grep -oi "\<segments\>" /dev/null example.c | sort | uniq -c 2 aa.c:segments
You can see here it found both segments, but didn't count segment. The
\> force matching only entire words.
THE_WORD123 does NOT match _THE_WORD_, word breaks are at non-alpha-numeric characters. FYI.