Reputation: 945
I am trying to sum two numbers of a table (in file) with awk (inside a loop), using variables passed from a bash script like described below. The numbers that I am dealing with ($value) are floating point values. $value only contains one number. Note that the line where the error occurs is 126, 125 is working fine.
111 while read line
112 do
120 n=2
121 sum=0
122
123 for x in $(seq 1 $number)
124 do
125 value=$(echo "$line" | awk -v n="$n" '{print $n}') # I am just getting the values to sum up here
126 sum=$(awk -v sum="$sum" -v value="$value" '{sum = sum + value; print sum}')
n=$((n+1))
129 done
done < $file
Where $number is defined previously.
I get the following error:
./script.sh: line 126: /bin/awk: Argument list too long
I am only trying to pass two variables on the awk command on this line, any idea why I am getting this error?
An example of the table in the "file":
A -0.717616 -0.623398 -0.214494 -0.352871
B -0.19373 -0.140626 -0.0523623 0.0248858
C -0.0822092 -0.302354 0.347158 -0.0373262
D 0.310213 0.312805 0.114366 0.353496
E -0.175354 -0.0263985 -0.125694 -0.155082
Thank you!
Upvotes: 0
Views: 553
Reputation: 531798
There are two problems with your call to awk
: you haven't specified an input file, so it is reading from its inherited standard input (which is the file the while
loop is also trying to read from), and it outputs each line it reads, not just the value of sum
(fixed while I was typing this).
This is a very inefficient way to add up the numbers in the file, by the way, but here is a corrected version:
while read line
do
n=2
sum=0
for x in $(seq 1 $number)
do
value=$(echo "$line" | awk -v n="$n" '{print $n}')
sum=$(awk -v sum="$sum" -v value="$value" 'BEGIN {sum = sum + value; print sum}' </dev/null)
n=$((n+1))
done
done < $file
A better solution:
awk 'BEGIN {sum=0}
{for (i=2;i<=NF;i++) { sum = sum + $i }}
END {print sum}' < $file
Upvotes: 1