-3

I have a data file:

1
2
3
4

Now I want to add the first and second number, second and third numbers and so on and receive the data file:

1 
2 3
3 5
4 7

And then remove the first row to get:

2 3
3 5
4 7

I could have used spreadsheet but I need to use gnuplot for plotting. So I really want to use awk for this task.

  • 3
    OK, so what is it you are having trouble with? This is a very simple, straightforward thing to do in awk. Which part of it is confusing you? What do you have so far? – terdon May 6 at 17:15
  • I have no experience using awk. That is the trouble. – physu May 6 at 17:16
  • 2
    Now could be a good time to gain that experience. If you get stuck we're here to help. – roaima May 6 at 17:18
2

This is really trivial in awk. By default, awk will read its input file and apply whatever script you tell it on each line. It will split the line on whitespace (by default, you can choose another delimiter using -F), and the first field will be $1, the second $2 and so on.

With this in mind, what you need is a simple script that i) saves the value of the previous line in a variable and ii) if we have a previous value (so, if this isn't the first line), prints the current first field plus the sum of the last line and the current first field. in other words, this:

$ awk '{if(last){print $1, $1+last;} last=$1}' file 
2 3
3 5
4 7

Or, equivalently

awk 'last != "" { print $1, $1 + last } { last = $1 }' file

or,

awk 'NR > 1 { print $1, $1 + last } { last = $1 }' file
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.