Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all files in a directory with a certain extension

Tags:

find

bash

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

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

The problem with this is that if there are no php files at all, the command that gets executed is ls -l, listing all files and directories, instead of 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 ends up returning the size of all entries in the event that there are no files matching the *.php pattern.

How can I guard against this event?

like image 611
xbonez Avatar asked Sep 16 '13 08:09

xbonez


3 Answers

I suggest you to firstly search the files and then perform the ls -l (or whatever else). For example like this:

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

and then you can pipe the awk expression to make the addition.

like image 179
fedorqui 'SO stop harming' Avatar answered Sep 27 '22 19:09

fedorqui 'SO stop harming'


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

find . -type f -name "*.php" -printf "%s\n" | paste -sd+ | bc
like image 28
devnull Avatar answered Sep 27 '22 19:09

devnull


Here is another way, using du:

find . -name "*.php" -type f -print0 | du -c --files0-from=- | awk 'END{print $1}'
like image 29
dogbane Avatar answered Sep 27 '22 19:09

dogbane