2

I want to see just last sum here, but it shows me everything.

awk '{print sum += $1} END {print sum}' file.dat

This is the output:

1.2
3.6
7.3
7.3
Eliah Kagan
  • 117,780
  • How is this Ubuntu-related? Seems like a good Stack Exchange question. (Hint: What do you expect the print statement in (print sum +=$1} to do?) – user535733 Nov 23 '17 at 20:00
  • 3
    @user535733 It would be rather odd if we considered this question off-topic, because shell scripting is on-topic here, and awk one-liners like this are clearly part of shell scripting. Furthermore, using external commands like sed and awk to process text line-by-line is the preferred practice in shell scripting; needlessly using shell builtins instead is somewhat discouraged. I, or someone else, can post an answer to this question, but do you want to? – Eliah Kagan Nov 23 '17 at 21:05
  • @EliahKagan fair enough. – user535733 Nov 23 '17 at 21:40

1 Answers1

2

Considering you want sums in file.dat added together and then print them out, the line should be:

awk '{sum +=$1} END {print sum}' file.dat

Telling awk to print the sum every time you add a new value to sum makes it show each intermediate value, just as you have experienced.

Videonauth
  • 33,355
  • 17
  • 105
  • 120