by vram22 · 9y ago · 0 comments
ls -lR /path/to/dir | awk ' { s += $5 } END { print s / 1024 " K" } '
$5 is the 5th field of the output, which is the file size field in the case of ls output. The code inside the first set of braces runs once for every line of input (which comes from standard input, so from the ls command, in this case), and the code inside the second set of braces runs at the end of the input, calculating and printing the desired result of the total of all file sizes for files found by ls, in kilobytes. It can easily be changed to output the total in bytes or megabytes by dropping the '/ 1024' or adding another one after the first. Variable s is initialized to 0 by default at the start.
You can get similar info with "du -hs /path/to/dir" but the ls plus awk pipeline lends itself to more customization, such as adding conditions for the type or owner of the file, etc.
find /path/to/dir -type f -printf "%s\n" | awk ' { s += $0 } END { print s " bytes" } '
The find command has much powerful file filtering capabilities than that of the ls command and works better with weird characters in filenames.
There is also the -print0 option to find to handle filenames with newlines in them.
-print0 may be non-POSIX and a GNU extension.
POSIX has -print, but interestingly, in some Unixes I have seen that not using -print still prints the filenames found, by default.
If no expression is present, -print shall be used as the expression. Otherwise, if the given expression does not contain any of the primaries -exec, -ok, or -print, the given expression shall be effectively replaced by: ( given_expression ) -print
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/fi...
You are correct regarding the GNU option -B, which would not be relevant here, and regarding the fact that neither of these options are in POSIX. Thanks for pointing out those limitations.