Reputation: 2353
I've to make a script which will be able to sum the columns. The file looks like that:
1 2 3
1 2
1
While executing script without the argument ./sum.sh
I get the sum of all the columns so the answer is 10. But I have to make it add only certain columns. For example ./sum.sh 1 3
should sum first and third column and give 6.
My code:
sum=0
if [[ $# -eq 0 ]]; then
awk '{for(i=1;i<=NF;i++) sum+=$i;}; END {print sum}' plik.txt
else
exit 0;
fi
while [ $# -gt 0 ]
do
awk '{sum +="$1"} END {print sum}' plik.txt
shift
done
I think that I'm quite close to the solution, but something must be missing.
Upvotes: 0
Views: 95
Reputation: 67547
here is a combination of your script and Kent's solution
#!/bin/bash
file=plik.txt
if [ $# -eq 0 ];
then
awk '{for(i=1;i<=NF;i++) sum+=$i}
END {print sum}' "$file"
else
awk -v cols="$*" 'BEGIN {split(cols,cs)}
{for(c in cs) sum+=$cs[c]}
END {print sum}' "$file"
fi
in action
$ ./sum.sh 1
3
$ ./sum.sh
10
$ ./sum.sh 1 3
6
$ ./sum.sh 1 2
7
$ ./sum.sh 1 2 3 4
10
$ ./sum.sh 1 2 3
10
Upvotes: 1
Reputation: 195229
This one liner should work:
awk -v c="1 3" 'BEGIN{split(c,cols)}
{for(x in cols)s+=$cols[x]}END{print "Sum:"s}' file
Note the c="1 3"
means the columns you want to do sum, space separated. It could be set by shell script variable: -v c="$var"
, the awk will do the calculation and output.
With your example file, the above one-liner outputs:
Sum:6
Upvotes: 2
Reputation: 1242
This is what I came up with, no bash
conditions required:
awk 'BEGIN{sum=0} {if(NF==1) sum+=$1;else for(i=1;i<=NF;i++) sum+=$i;} END{print sum}' plik.txt
Upvotes: 0