To count the matches, listing only the filename(s) and count:
grep -src HOST /etc/*
Example output:
/etc/postfix/postfix-files:1
/etc/security/pam_env.conf:6
/etc/X11/app-defaults/Ddd.3.3.11:1
/etc/X11/app-defaults/Ddd:1
/etc/zsh/zshrc:0
/etc/zsh/zshenv:0
The -c
option supresses normal output and prints a match count for each file.
If you'd like to suppress the files with zero counts:
grep -src HOST /etc/* | grep -v ':0$'
To print the line number (-n
) and file name (-H
) for each matching line for any number of input files:
grep -srnH HOST /etc/*
Example output:
/etc/lynx-cur/lynx.cfg:254:.h2 LYNX_HOST_NAME
/etc/lynx-cur/lynx.cfg:255:# If LYNX_HOST_NAME is defined here or in userdefs.h, it will be
/etc/X11/app-defaults/Ddd.3.3.11:8005: DDD 3.3.11 (@THEHOST@) gets @CAUSE@\n\
/etc/X11/app-defaults/Ddd:8010: DDD 3.3.12 (@THEHOST@) gets @CAUSE@\n\
The option -r
causes grep
to recursively search files in each subdirectory at all levels under the specified directory. The -s
option suppresses error messages.
To suppress matches of binary files, use the -I
option.
See man grep
for more information.
Not a fundamental speed-up but at least something :)
find . -printf \\n | wc -l
You really do not need to pass the list of file names, just the newlines suffice. This variant is about 15 % faster on my Ubuntu 12.04.3 when the directories are cached in RAM. In addition this variant will work correctly with file names containing newlines.
Interestingly this variant seems to be a little bit slower than the one above:
find . -printf x | wc -c
Special case - but really fast
If the directory is on its own file system you can simply count the inodes:
df -i .
If the number of directories and files in other directories than the counted one do not change much you can simply subtract this known number from the current df -i
result. This way you will be able to count the files and directories very quickly.
Best Answer
First you would use the
find
command in the terminal.find . -type f -name "*.what"
That will list all files on the system from the current directory "." matching "type: file" and name "*.what".
So you can incorporate that into a bash script, like so:
Edit
Here you go, this does what you want I think.
That will output the number of files in any directories that contain *.what (recursively). The number if files excludes directories
!/^d/
and the *.what file!/*.what/
.That should get you there. Works on my system at least, assuming I understand the question.