5

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
monk
  • 1,953
  • 3
  • 21
  • 41

5 Answers5

10
$ 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
James Brown
  • 36,089
  • 7
  • 43
  • 59
5

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.

Inian
  • 80,270
  • 14
  • 142
  • 161
5
$ 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
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
4

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
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

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.

Guy
  • 637
  • 7
  • 15