DEV Community

Sérgio Araújo
Sérgio Araújo

Posted on

Sum Last Field Using Vim

Let's say you have

val:1 5.50
this line has 6.70
this one, even more, fields 10.15
Enter fullscreen mode Exit fullscreen mode

Using awk you refer to the last column with $NF. So after saving the file we can save the result ina variable

:let @a = system("awk '{t+=$NF} END {print t}' file.txt")
Enter fullscreen mode Exit fullscreen mode

Now we insert the value with:

:put a
Enter fullscreen mode Exit fullscreen mode

Or on insert mode

<Ctrl-r>a
Enter fullscreen mode Exit fullscreen mode

A more simple solution

:r!awk '{t+=$NF} END {print "Total: " t}' %

:r ................... read to next line
awk .................. awk command
t  ................... variable to store total
$NF .................. last field
% .................... current file
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)