Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a separator if value or two consecutive rows do not match for a column

Tags:

bash

awk

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
like image 632
monk Avatar asked Jan 30 '18 13:01

monk


4 Answers

$ 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
like image 150
James Brown Avatar answered Nov 14 '22 23:11

James Brown


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.

like image 5
Inian Avatar answered Nov 14 '22 22:11

Inian


$ 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
like image 5
Akshay Hegde Avatar answered Nov 15 '22 00:11

Akshay Hegde


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
like image 4
RavinderSingh13 Avatar answered Nov 14 '22 23:11

RavinderSingh13