Unix regex to add content to file
4 answers
I believe the following is what you are looking for. It sums the last field in each record for the data that is read from stdin.
awk '{ sum += $NF } END { print sum }' < file.txt
Some notes:
- With awk, you don't need to declare variables, they are inherited by assigning values to them.
- Variable
NF
is the number of fields in the current record. By adding it with $, we treat its value as a variable. At least that's how it works :) - The block
END { }
is executed only after all records have been processed by other blocks.
+4
a source to share
An awk
script is all you need to do this since it has objects grep
built in as part of the language.
Let's say your actual file consists of:
asdfb zz 1
adfsdf yyy 2
sdfdf xx 3
and you want to sum the third column. You can use:
echo 'asdfb zz 1
adfsdf yyy 2
sdfdf xx 3' | awk '
BEGIN {s=0;}
{s = s + $3;}
END {print s;}'
The BEGIN clause runs before any lines are processed, the END clause after all lines are processed.
A different suggestion happens for each line, but you can add additional suggestions to change the behavior based on all things ( grep
-py things).
+1
a source to share