How to add the sum of any column value to the last column of the last record in a tab delimited file

I need to take the sum of col2 and add the value to the last column of the last record. Please advice on how we can achieve this using the UNIX shell script.

Eg Input file: Col1 Col2 Col3 Col4 abc 2 A null bcd 3 B null adf 4 C null Output file Col1 Col2 Col3 Col4 abc 2 A null bcd 3 B null adf 4 C 9 
+4
source share
3 answers

Assuming you want to keep a space in your output:

 $ awk '{sum+=$2; s=s $0 ORS} END{ sub("null"ORS"$",sum,s); print s}' file Col1 Col2 Col3 Col4 abc 2 A null bcd 3 B null adf 4 C 9 

or

 $ awk '{sum+=$2; printf "%s",p} {p=$0 ORS} END{ sub("null$",sum); print}' file Col1 Col2 Col3 Col4 abc 2 A null bcd 3 B null adf 4 C 9 
+1
source

This awk script will do this, I think:

 awk '{sum+=$2; if (NR != 4) print; } END {$4=sum; print;}' infile 

EDIT: Or even better:

 awk '{sum+=$2; if (NR>1) print x; x=$0} END {$4=sum; print $0;}' infile 
0
source

Here is one way: GNU awk :

 awk -v last="$(wc -l < file.txt)" 'NR == 1 { print; next } { sum += $2 } NR == last { sub($NF, sum) }1' file.txt 

Results:

 Col1 Col2 Col3 Col4 abc 2 A null bcd 3 B null adf 4 C 9 
0
source

Source: https://habr.com/ru/post/1443316/


All Articles