10

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?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Ayush
  • 41,754
  • 51
  • 164
  • 239
  • Possible duplicate of [How to find all file extensions in directory?](https://stackoverflow.com/questions/4998290/how-to-find-all-file-extensions-in-directory) – jww Jan 23 '18 at 23:11

3 Answers3

19

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Ah, thanks. I was earlier doing `find . -name "*.php" -type f | xargs ls -l`, but facing the same problem. – Ayush Sep 16 '13 at 08:36
  • Most of times it is not necessary to pipe `xargs` after `find`. The `exec` command gives you this utility. Note that it is necessary to use `{}` to refer to the file name found by `find`. – fedorqui Sep 16 '13 at 08:47
8

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
devnull
  • 118,548
  • 33
  • 236
  • 227
  • This is really cool as well. I didn't even know about the existence of `paste` and `bc`. – Ayush Sep 16 '13 at 08:41
1

Here is another way, using du:

find . -name "*.php" -type f -print0 | du -c --files0-from=- | awk 'END{print $1}'
dogbane
  • 266,786
  • 75
  • 396
  • 414