0

I'm stuck at figuring out how to sum ls 5th column result with awk. If I add $bytesum+=... then the program obviously breaks. Any ideas?

bytesum=0
for i in `cat fileextensions.txt | sort | uniq`
do
    ls -Rl "$folder" | grep $i | awk '{bytesum+=$5}; {print $9 " " $5}'
done

echo $bytesum
gici
  • 3
  • 2
  • See https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice, http://porkmail.org/era/unix/award.html, https://mywiki.wooledge.org/ParsingLs, https://mywiki.wooledge.org/Quotes, and http://mywiki.wooledge.org/BashFAQ/082 for some of the issues with that script. Also sort | uniq = sort -u and grep foo | awk '{bar}' = awk '/foo/{bar}' and you don't need separate blocks for every action in awk - {x}; {y} = {x; y} and print $9 " " $5 = print $9, $5 (it's why OFS exists). And where did $folder come from? – Ed Morton Apr 10 '20 at 12:54
  • $folder is a path to the folder where the script recursively searches for files with given extensions. – gici Apr 10 '20 at 13:11
  • Then add its definition to the script in your question. – Ed Morton Apr 10 '20 at 13:14
  • What is the contents of fileextensions.txt and do you really need that as a file? – Kusalananda Apr 10 '20 at 14:39

2 Answers2

0

In bash:

for size in `du *.jpg | cut -f1`; do sum=$((sum+size)); done; echo $sum

Integrate this into yor main loop changing the .jpg in my example to a proper variable $i in your script.

0

With GNU find all you need is:

find . -type f -printf '%s\n' | awk '{s+=$0} END{print s+0}'

With any find:

find . -type f -exec stat -c '%s\n' {} \; | awk '{s+=$0} END{print s+0}'

To just find and stat files with a specific extension in a specific directory ("folder" is a Windows term, in UNIX terminology it's a directory) as it looks like you might be trying to do would be:

dir='whatever'
ext='pdf'
find "$dir" -type f -name "*.${ext}" -printf '%s\n'
Ed Morton
  • 31,617