How do I write awk '{print $1+$2+$3} file1 > file2 for n columns instead of 3?
You want to compute the sum of the fields for each record, so it's just:
awk '{sum = 0; for (i = 1; i <= NF; i++) sum += $i; print sum}' < file1 > file2
The curly braces begin an action statement that is executed on every line of the input; there is no preceding condition that would limit its execution to lines that satisfy such a condition.
On each line:
- Initialize a
sum
variable to zero. - Loop through the fields, starting at field #1 and ending at the last field (the special variable
NF
), and incrementsum
by the value of that field ($i
). - Print the value of the
sum
variable.