How can I count the number of files (in a directory) containing a given string as input in bash/sh?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
grep -l "string" * | wc -l will search for “string” in the contents of all files in the working directory and tell you how many matched.
Method 2
greps parameter -l will only output the filenames which are matching $PATTERN, wc can count them afterwards.
grep -l "$PATTERN" * | wc -l
Method 3
awk '/pattern_to_look_for/ {s+=1; nextfile;} END {print s}' *
Clarification: This looks for the number of files that has the “pattern_to_look_for” in their contents and not in their filenames (like Wag’s answer). From your question it’s hard to tell what you are looking for.
Method 4
This works in Bash with any filename:
grep -lZ "$pattern" * | tr -cd '00' | wc -c
Explanation:
grep‘s-Zoption prints every result with a ␀-byte separator. This character can’t be part of a file name, so we can simply count the number of separators to get the number of files.- To get rid of the other characters in the output, we simply remove everything except the ␀ bytes using
tr. - Then just count the characters with
wc.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0