0

I want to create a new column in my file that sums the values of the 2nd and 3rd column for each line. For example I want

1 2 3
4 5 6 
7 8 9

to give me

1 2 3 5
4 5 6 11
7 8 9 17

I've seen other posts doing it with awk but I want to know if there is a way of doing it with loops so that it will read each line and perform the task and then move to the next line. I've saved my values into example.txt and tried the following but it didn't work:

for n in [ test1.txt | wc -l ] 
do
    test1.txt$2 + test1.txt$3 > test1.txt$4
done
1
2

You could do

$ while read a b c; do 
    printf '%d %d %d %d\n' "$a" "$b" "$c" "$((b+c))"
  done < test1.txt
1 2 3 5
4 5 6 11
7 8 9 17

but don't - see Why is using a shell loop to process text considered bad practice?

If your shell's read builtin provides array-reading functionality, you could do something like this (in bash):

$ while read -a vals; do 
    vals+=( $((vals[1] + vals[2])) )
    printf '%d %d %d %d\n' "${vals[@]}"
  done < test1.txt
1 2 3 5
4 5 6 11
7 8 9 17

(but don't do that, either).

1
awk '{ $4=$3+$2; print }' inputfile
2
  • is there a way to do it without awk and do it with loops? – Parnian Oct 15 '20 at 20:07
  • awk is doing it with loops. It uses a loop to parse the input file. But if you really wanted to you could use something like { sum=0; for (i=2; i<=3; i++) { sum += $i } $4=sum; print} – DopeGhoti Oct 15 '20 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.