I have to search a file for lines with some specific words and edit these lines as follows. The other lines should remain the same. For example:
eltu r21, r24, r23 brz r21, outer_end add r27, r0, r25 jp outer_end add r27, r0, r22 outer_end:
to be modified to:
eltu r21, r24, r23 line2: brz r21, $(outer_end-line2) add r27, r0, r25 line4: jp $(outer_end-line4-4) add r27, r0, r22 outer_end:
Can any one please help how to use AWK to achieve this.
Regards
Advertisement
Answer
awk solution:
$ cat tst.awk /brz|jp/{ last=$NF; NF--; printf("line%s:t%s $(%s-line%s)n", NR, $0, last, NR); next } NF>1{ print $0; next } { print $1 }
Explanation:
When brz
or jp
matches, save last field in last
, remove last field with NF--
and print the resulting line.
If it is a line containing multiple fields NF>1
then just print it.
Last possibility is a label line, only the first field needs to be printed.
In action:
awk -f tst.awk input.txt eltu r21, r24, r23 line2: brz r21, $(outer_end-line2) add r27, r0, r25 line4: jp $(outer_end-line4) add r27, r0, r22 outer_end: