So what I have to do is find all regular files within and below the directory. For each of these regular files, I have to egrep for pattern($ARG) and find out if the output of the file matches the pattern ($ARG), if it does it will add one to the counter.

What I have so far is the file command:

$count = 0
file *

However, I am having trouble getting egrep &ARG > /dev/null/ ; echo $? to run through each file that appears from (file *).

I understand that file * | egrep directory > /dev/null ; echo $? will output 0 because it find the pattern 'directory' in the file, but am having trouble getting it to loop through each regular file so I can add one to the counter every time the pattern is matched.

  • 1
    If you just want to count the files which contain the pattern, the following will show it: find -type f -print0|xargs -0 egrep -l ...|wc -l, where ... is the parameter list you want to pass to egrep. This finds all standard files in the current directory and below, and this list is built into a file list for egrep -l, which shows the name of any file containing the match pattern, and the number of files is counted by wc -l. – AFH Apr 14 '16 at 1:47
  • Your question is very confusing, would you mind rewording it? What do you intend to achieve with file *? file returns the type of file(s) specified in its arguments. What do you intend with this? as @AFH states above, the best tool for obtaining all files within a directory is find. – Ziggy Crueltyfree Zeitgeister Apr 14 '16 at 8:21

I think this will do what you want. Essentially, it creates a list of all the files in the directory and below; then scans them, printing the file name of any hits; then it counts how many file names are returned.

count=$(egrep -l "$ARG" $(find . -type f) | wc -l)

It is possible that the find will return too many files (you will get the error, "Argument list too long"). In which case, this slower, but surer mechanism will work:

count=$(find . -type f -exec egrep -l "$ARG" {} \; | wc -l)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.