1

I am working on a shell script that will read the lines of a file, in reverse. I need it to subtract the previous line from the latter, but only if the latter is larger. If it's smaller, then I just want the number on that line.

Example:

File contents:

100
200
300
100
300

Results should be:

200     # line 5 - line 4    
100     # line 4 (as it's < line 3) 
100
100

The code I was using simply to subtract the lines previously (without taking into account if value was >= was:

awk 'p{print $0-p}{p=$0}' inputfile > outputfile

I need to still do this, but only if value is greater than previous line.

I was thinking of using a while read loop, but assigning a variable to each line for comparison, or something similar, is really taxing my brain. Thanks in advance!

1

tac is useful to reverse the line order of a file - (also BSD tail -r can reverse the line order)

tac file | awk 'p { if( p>$1 ) print p-$1; else print p } { p=$1 }' 

If, for some reason, you can't use tac or want to use awk exclusively, you can use awk to read the entire file into memory via an array, and END{} process the array in reverse order.

awk '{ r[i++]=$0};  END{ for(i=i-1; i>=0; i--) 
       if( r[i+1] ) if( r[i+1]>r[i] ) print r[i+1]-r[i]; else print r[i+1] 
     }' file
  • A more terse version for the awk part of your first solution can be awk 'p{print (p>$0)?p-$0:p}{p=$0}'. – h.j.k. Aug 19 '15 at 2:25
  • Thanks! I used the first one above "tac file | awk .....". Works perfectly! – Tyler Aug 19 '15 at 12:40
0

You can use tac to reverse file and then awk for calculation. I've modified your file to make lines more random.

$ cat file
101
220
303
140
305
$ tac file | awk '{if(last>$0)print last-$0;else print last;last=$0}END{print last}'

165
140
83
119
101

Two remarks:

  • After all you need to remove first line (empty line) if you don't need it.
  • In the END{} block the very first line from the file is printed, remove this block if you don't want that.

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.