Linux – Find file matching extension, then count files in the found directory

findlinux

I am trying to search the filesystem for all files matching an extention (*.what), then count all files in the directory where it found the *.what files. The output should contain the directory name and filenames with count.

How can this be done?

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.

#!/bin/bash

src=${1:-"."}
ext=${2:-"what"}

for dir in `find ${src} -type f -name "*.${ext}"`; do
    dir=`echo ${dir} | awk 'BEGIN{FS=OFS="/"}{$NF=""}{print}'`
    echo ${dir} "has" `ls -l ${dir} | awk '!NR=1 && !/^d/ && !/*.what/ {print $NF}' | wc -l` "file(s)"
done

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.

Related Question