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
✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025

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")
✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025

Now we insert the value with:

:put a
✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025

Or on insert mode

<Ctrl-r>a
✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025

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
✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/sum last field using vim e - Kapook Update 2025

Top comments (0)