Reputation: 2115
I have input like following and I need to put a separator between the rows if the value of the third column between two rows is different.
one two three four
five six three seven
eight nine ten elevel
alpha beta ten gama
tango charlie oscar bla
Expected result:
one two three four
five six three seven
=
eight nine ten elevel
alpha beta ten gama
=
tango charlie oscar bla
Here is what I thought would work but its not.
awk '{col3=$3;next} $3!=col3{$0="\n="$0;print $0}' input
Upvotes: 5
Views: 164
Reputation: 16997
$ awk 'p!=$3{if(NR>1)print "="; p=$3}1' file
one two three four
five six three seven
=
eight nine ten elevel
alpha beta ten gama
=
tango charlie oscar bla
Upvotes: 5
Reputation: 133680
Following awk
may help you too in same.
Solution 1st: With conditions checking and having prev
variable in it:
awk 'prev!=$3 && prev{print "="} 1; {prev=$3}' Input_file
Solution 2nd: with use of printf
and checking condition in it.
awk '{printf("%s%s",prev!=$3 && prev?"=" RS $0:$0,RS);prev=$3}' Input_file
Upvotes: 4
Reputation: 647
I'm going to add that the problem with your initial solution was the following:
{
col3=$3;
next;
}
As this was the first action, for every line, the variable col3
would be set to field 3, before the next
keyword would skip the second action for all lines.
Upvotes: 2
Reputation: 85800
Another variant in Awk
complementing James's answer (or just the same? written differently),
awk '{ if ($3 != old && NR>1) { print "=" } print; old = $3; }' file
The idea is basically to backup the $3
from each line and basically if it varies in the next print the string needed. The NR>1
is just a condition to skip printing for the first line.
Upvotes: 5
Reputation: 37454
$ awk '$3!=p && NR>1 { print "=" } { print; p=$3 }' file
one two three four
five six three seven
=
eight nine ten elevel
alpha beta ten gama
=
tango charlie oscar bla
Upvotes: 10