Awk to compare the current line with the next line and print one of the lines based on the condition

I have an input file that looks like this (the first column is the number of the place, and the second is the account, which should increase over time):

1 0 1 2 1 6 1 7 1 7 1 8 1 7 1 7 1 9 1 9 1 10 1 10 1 9 1 10 1 10 1 10 1 10 1 10 1 10 1 9 1 10 1 10 1 10 1 10 1 10 1 10 

and I would like it to be like this (the number of substitutes decreased with the previous count):

 1 0 1 2 1 6 1 7 1 7 1 8 1 8 1 8 1 9 1 9 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 1 10 

I try to use awk for this, but stumble with getline, since I cannot figure out how to reset the line number (NR?), So it will read each line and the next line, not two lines at a time. This is the code that I still have, any ideas?

 awk '{a=$1; b=$2; getline; c=$1; d=$2; if (a==c && b<=d) print a"\t"b; else print c"\t"d}' original.txt > fixed.txt 

Also, this is the result that I am currently getting:

 1 0 1 6 1 7 1 7 1 9 1 10 1 9 1 10 1 10 1 9 1 10 1 10 1 10 
+8
awk getline
source share
2 answers

Perhaps all you need is:

 awk '$2 < p { $2 = p } { p = $2 } 1' input-file 

This will crash in the first row if the value in the second column is negative, and do the following:

 awk 'NR > 1 && $2 < p ...' 

This simply sets the second column to the previous value if the current value is less, then stores the current value in the p variable, then prints the row.

Note that this also slightly changes the output interval on lines that change. If your entry is tabbed, you might want to do:

 awk 'NR > 1 && $2 < p { $2 = p } { p = $2 } 1' OFS=\\t input-file 
+7
source share

This script will do what you like:

 { if ($2 < prev_count) $2 = prev_count else prev_count = $2 printf("%d %d\n", $1, $2) } 

This is an extended version that is easy to read :)

+2
source share

All Articles