Bash: total size of file in current directory matc

2019-08-04 10:46发布

问题:

ls | grep -P "$1" | awk '{ x += $5 } END { print "total bytes:" x }' 

This code is returning 0 using "[0-9]" as reg expr, in current folder there are 2 files named: "1" and "6", each one with size of 138bytes.

Anyone could help me to find the problem?

回答1:

You're just missing the -l option to ls.

ls -l | grep -P "$1" | awk '{ x += $5 } END { print "total bytes:" x }' 


回答2:

du can help you with this; it has a -c flag for displaying a "grand total". It results in a final line containing the total size followed by the word total. Therefore, the following should give you the total size in bytes for your selection:

du -bc yourFilePattern | awk 'END {print $1}'

EDIT:

If something like *pattern* is not enough and you want a regex, just use:

ls | grep -P "$regex" | xargs du -bc | awk 'END {print $1}'


标签: bash shell sh