Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing consecutive rows in awk

Tags:

compare

awk

I would like to compare consecutive rows in a file using awk command. Here is an example of input and output.

Input file

6    
7    
8    
9    
10    
4    
5    
6

The output file I wanted to have is like this:

6
7
8
9
10 
14 
15 
16  

Basically I wanted to compare if the current line is greater than the previous one and continue to print both the previous and the current lines. As soon as the current line is less than the previous one, add a value (10) to each of the subsequent lines.

like image 717
Yacob Avatar asked Jan 20 '26 11:01

Yacob


1 Answers

Updated as per request in comment:

awk '{if ($1<prev) {offset++}; print ($1+(offset*10)); prev=$1}' input_file

This will now increase the increment offset by 10 each time you go from a larger number to a smaller number between consecutive lines.

like image 52
sampson-chen Avatar answered Jan 23 '26 19:01

sampson-chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!