Help with awk script to append seq num at end of record

Hi Unix forum.

I have the following requirement to add a sequence value to each record in a file but only if it meets certain conditions. Field value in pos. 1 and 2 must be '0B' or 'OA' else leave as is. Sequence value must be preserved for each OB and OA pair.

Data Before:
123
456
OB123
OA456
OB789
OA890
999

Data After:
123
456
OB123 1
OA456 1
OB789 2
OA890 2
999
This is what I have so far but it's not working 100% as expected.  It's adding the sequence value to the last record also.

awk '{var0=substr($0,1,2)} var0=="AB" {COUNTER = COUNTER+1} {$0 = $0 FS COUNTER} {var1=substr($0,1,2)} var1=="AO" {$0 = $0 FS COUNTER} 1' 

Can someone help me refine my code?

Thank you.

Hi,

Can you try this ?

awk 'BEGIN {i=1;j=1} {a=substr($0,1,2);if (a == "OA") { print $0,i++;} else if (a == "OB") print $0,j++; else print $0 } ' file 
cat file
123
456
OB123
OA456
OB789
OA890
999
OA346
OB709

output :

123
456
OB123 1
OA456 1
OB789 2
OA890 2
999
OA346 3
OB709 3

Non-awk :

 i=1;j=1;while read line; do if [[ "$line" == OA* ]]; then echo $line $(( i++ )); elif [[ "$line" == OB* ]]; then echo $line $((j++)); else echo $line; fi; done < file

Hi,
This works fine :

$ cat 123.txt
123
456
OB123
OA456
OB789
OA890
999
$ awk '/^OA/{print $0,++a }/^OB/{print $0,++b} !/^O[AB]/' 123.txt
123
456
OB123 1
OA456 1
OB789 2
OA890 2
999

Thank you guys - I will try your suggested code.

Hello pchang,

Could you please try following too and let us know if this helps.

awk '{printf("%s %s\n",$0,$0=$0~/OA/?++A["OA"]:($0~/OB/?++A["OB"]:""))}'   Input_file

Thanks,
R. Singh

Hi Ravinder.

it looks like this code works too.

Thanks for providing additional code option.