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

I have an input like the following, and I need to put a separator between the rows if the value of the third column between the 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 

This is what I thought, but it is not.

 awk '{col3=$3;next} $3!=col3{$0="\n="$0;print $0}' input 
+5
source share
5 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 
+9
source

Another option in Awk that complements James's answer (or written differently in the same way),

 awk '{ if ($3 != old && NR>1) { print "=" } print; old = $3; }' file 

The idea is basically to back up $3 from each line, and basically, if it changes in the next print, a line is needed. NR>1 is simply a skip condition for the first line.

+5
source

The following awk can help you with that too.

Solution 1st: With a check of conditions and the presence of the prev variable in it:

 awk 'prev!=$3 && prev{print "="} 1; {prev=$3}' Input_file 

2nd solution: using printf and checking in it.

 awk '{printf("%s%s",prev!=$3 && prev?"=" RS $0:$0,RS);prev=$3}' Input_file 
+4
source
 $ 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 
+4
source

I want to add that the problem with your original solution was this:

 { col3=$3; next; } 

Since this was the first action, for each row, the variable col3 would be set to field 3 before the next keyword skips the second action for all rows.

+2
source

Source: https://habr.com/ru/post/1275044/


All Articles