2

I have five files each with a number in the first line.

I am attempting to write a bash script incorporating a for-loop that can calculate both the number (count) of the files and the sum of the numbers within in the files.

This is what I have attempted so far:

for file in $* 
do
        $[head -1 $file] 
        echo $(head -1) 
done

I am unsure how to incorporate a sum and count element as yet.

2
  • Can you provide example context of file and expected output? Commented Feb 6, 2019 at 12:16
  • I am teaching myself for-loops. I have five files labeled file1,..,file5. The first entry of each file is a number. I would like to write a loop that a) adds all the numbers up and prints a sum b) reports the number of files it went through (ie the count).
    – marzo
    Commented Feb 6, 2019 at 21:35

2 Answers 2

6

I guess what you are trying to do can be achieved by this:

#!/bin/bash
sum=0
count=0
for file in "$@"
do
        number=$(head -1 "$file")
        count=$((count + 1))
        sum=$((sum + number))
done
echo "The sum of the $count file(s) is: $sum"

You just add variables to store the sum and the count of the files you are working with. You then increase the count each time you run through the loop. Also we add the number at the beginning line of the file to our sum-variable.

1
  • 3
    This doesn't work then there's a pipe. Ex: ls *.count | while read file
    – coolaj86
    Commented Jun 25, 2019 at 21:43
2

You could also do this with awk, avoiding the need to for head for each file:

gawk '{count += 1; sum += $1; nextfile} 
      END {printf "count: %d\t sum: %d\n", count, sum}' *

The first rule increments the count and sum, and then jumps to the next file, thus ignoring all but the first line of each file. In the END, we print out the numbers.

nextfile is a GNU thing, it might not work in other versions of awk. Another alternative would be to explicitly work only on the first line:

awk 'FNR == 1 {count += 1; sum += $1} 
      END {printf "count: %d\t sum: %d\n", count, sum}' *

This would however read the files in full, even if it doesn't do anything with the rest of the lines.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.