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

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay