Inserting some text if a field in the last column changes

Hi,

I have a file which looks like this:

A 01 00
B 02 00
C 04 00
D 00 01
E 01 01
F 02 01
G 01 04
H 02 04

I want to insert some text if the field if the last column changes. It should look like this:

Value 00
A 01 00
B 02 00
C 04 00
Value 01
D 00 01
E 01 01
F 02 01
Value 04
G 01 04
H 02 04

I tried using the following loop:

      while read line
      do
      NEW_VALUE=`echo "$line" | gawk '{printf $NF}'`
      if [ "$NEW_VALUE" != "$OLD_VALUE" ]; then
         echo Value "$NEW_VALUE" >> $tmp
      fi
      echo "  $line" >> $tmp
      OLD_VALUE="$NEW_VALUE"
      done < $file

However, this loop runs slow. Do you have any ideas?

Thanks in advance

Try this:

awk 'NR==1 || v != $3 {v=$3; print "Value " v}1' $file > $tmp
1 Like

Thank you very much, it works great!

However, I have another question. Is it possible to cut the last column of the file and to use some loop in this gawk function which will print the exact amount of the same chars (dashes) which are followed by a space and some amount of dashes? So it should look like this (let's assume that we declared in a variable the amount of dashes =9 which are followed by 4 dashes:

Value 00
--------- ----
A 01
B 02
C 04
Value 01
--------- ----
D 00
E 01
F 02
Value 04
---------
G 01
H 02

Thanks in advance

I'm sorry, i made a mistake in that place. Of course, it should look like this:

Value 00
--------- ----
A 01
B 02
C 04
Value 01
--------- ----
D 00
E 01
F 02
Value 04
--------- ----
G 01
H 02

Try this...

var=9
awk -v VM="$var" '{if (NR==1 || v != $3) {v=$3; print "Value " v;$3="";{for(i=1;i<=VM;i++) {printf "-"}{print " ----"}}} else{$3=""}}1' file
1 Like

Thank you very much, it works perfectly!