2

I saw this question, and I want to do something similar: Print line if value in column changes

Essentially, I'll have a (tab-delimited) file like this

A 0 10 loss
A 10 20 loss
A 20 30 loss
A 30 40 no
A 40 50 no
A 50 60 no
A 60 70 no
A 70 80 gain
...

and I want to print both lines where the column 4 changes from (e.g.) "loss" -> "no" or "no" -> "gain", so the output would be

A 20 30 loss
A 30 40 no
A 60 70 no
A 70 80 gain

The value in the column 4 could be anything, but I want to print both lines bracketing the change.

This looks like something I could do with awk, but I'm not too familiar with it.

3 Answers 3

2

With awk, you could do:

awk 'BEGIN  { getline; cmp=$4; preline=$0 }
     cmp!=$4{ print preline, $0 } { cmp=$4; preline=$0 }' OFS='\n'  infile
A 20 30 loss
A 30 40 no
A 60 70 no
A 70 80 gain

In BEGIN block we read the first line and save the column#4 in variable named cmp and whole line into preline; later compare previous line's column4 with current line's, if there was changes then print both preline value and the current line read $0; the next block is just updating the current line's column4 and the whole line again as previous line for the next run.

1

Using the sed editor of the GNU variety we can do it as follows:

sed -Ee '
    $d;N
    /\s(\S+)\n.*\s\1$/!p
    D
' input.file

We carry two lines in the pattern space at all times, N, and look for the transition of the last field. Soon as we detect one, /\s(\S+)\n.*\s\1$/!p, we print the whole of the pattern space. Then we delete the first portion, D of the pattern space in both the scenarios of transition or no transition, since the use of the first portion is over at that stage.

Control transfers to the top of sed code and in case we are not yet at the eof, we repeat this procedure all over again. Eof halts the operation, $d.

Output:

A 20 30 loss
A 30 40 no
A 60 70 no
A 70 80 gain
1

Why not:

$ awk '(NR > 1) && (LAST !~ $4 "$") {print LAST; print $0} {LAST = $0}' file
A 20 30 loss
A 30 40 no
A 60 70 no
A 70 80 gain

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .