Reputation: 657
I need help with my bash script.
The task is counting total size of files in directory. I already did it ( using ls, awk and grep). My output may look like this for example:
1326
40
598
258
12
$
These numbers means size of files in directory. I need to count them all and I stuck here. So I would be really grateful if someone could tell me how to count them all (and find the total size of files in directory)
Thank you
Upvotes: 1
Views: 77
Reputation: 24802
well, in Unix shell programing, never forget the most basic philosophy, being:
which is the French for Use the right tool that does one thing, but does it well. You can achieve to do what you want with a mix of ls
or find
, and grep
, and awk
, and cut
, and sed
and …, or you can use the tool that has been designed for calculating files sizes.
And that tool is du
:
% du -chs /directory
4.3G /directory
4.3G total
Though, it will give the total size of every file within every directory of the given path. If you want to limit it to just the files within the directory (and not the ones below), you can do:
% du -chsS /directory
3G /directory
3G total
For more details, refer to the manual page [man du
], and here are the arguments I'm using in the answer:
-c, --total produce a grand total
-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
-s, --summarize display only a total for each argument
if you remove -s
you'll have the size details for each file of the directory, if you remove -h
you'll have full size in bytes (instead of rounding into a more readable form), if you remove -c
you won't have the grand total (i.e. the total
line at the end).
HTH
Upvotes: 2
Reputation: 67507
awk
to the rescue!
awk '$1+0==$1{sum+=$1; count++} END{print sum, count}'
adds up and counts all the numbers ($1+0==$1 for a number, but not for a string) and print them the sum and count when done.
Upvotes: 1