List all files in a directory with a specific extension

Let's say I want to list all the php files in a directory, including subdirectories, I can run this in bash:

ls -l $(find. -name *.php -type f)

The problem is that if there are no php files at all, the command that runs, ls -l , lists all the files and directories, not none.

This is a problem because I'm trying to get the combined size of all php files using

ls -l $(find . -name *.php -type f) | awk '{s+=$5} END {print s}'

which ultimately returns the size of all records if there are no files matching the *.php pattern.

How can I protect myself from this event?

+7
bash find
source share
3 answers

I suggest you search for files first and then do ls -l (or something else). For example, for example:

 find . -name "*php" -type f -exec ls -l {} \; 

and then you can pass the awk expression to add.

+16
source share

If you want to avoid parsing ls to get the total size, you can say:

 find . -type f -name "*.php" -printf "%s\n" | paste -sd+ | bc 
+8
source share

Here is another way: du :

 find . -name "*.php" -type f -print0 | du -c --files0-from=- | awk 'END{print $1}' 
+1
source share

All Articles