awk line instance counter

I Have a text file with several thousand lines of text.
Occasionally there will be a "sysAlive" line of text (every so often)
What would be an awk command to print every line of text, and to put in incrementing counter ONLY on the "sysAlive" lines

For example:

>cat file.txt
lineAAA a b c d x
lineBBB CCC DDD
lineEEE XYZ
this line contains the word sysALive
lineFFF aaa bbb ccc
lineGGG nnn nnn jjj
this line contains the word sysALive
lineHHH III J k L M n
line OOOPPPOOO
this line contains the word sysAlive
line thats enuff

I want this to look like:

>cat file2.txt
lineAAA a b c d x
lineBBB CCC DDD
lineEEE XYZ
this line contains the word sysALive 1
lineFFF aaa bbb ccc
lineGGG nnn nnn jjj
this line contains the word sysALive 2
lineHHH III J k L M n
line OOOPPPOOO
this line contains the word sysAlive 3
line thats enuff

The keyword (sysAlive) is always in the same field.
something like

awk print$0, and if $6="sysAlive" print $0(i) and increment i+1

Sorry for the crude example.
Any help is greately appreciated,
take care

Hello ajp7701,

I can see you said you are looking for exact string sysALive , but you showed in output as 3 when it comes sysAlive , so keeping this in mind and considering that it is not a typo. Following may help you then.

 awk '($0 ~ /sysA[lL]ive/){A++;print $0 OFS A;next} 1' Input_file
 

Output will be as follows.

lineAAA a b c d x
lineBBB CCC DDD
lineEEE XYZ
this line contains the word sysALive 1
lineFFF aaa bbb ccc
lineGGG nnn nnn jjj
this line contains the word sysALive 2
lineHHH III J k L M n
line OOOPPPOOO
this line contains the word sysAlive 3
line thats enuff
 

Thanks,
R. Singh

1 Like

yes that is 3. I cut and pasted, I dont know how that happened. ?? SRRY :frowning:

Since you want to count both sysAlive and sysALive , I assume you want a case insensitive match on the entire word. The following will count that string no matter which field it is in as long as it is a standalone word:

awk '/(^|[[:space:]])[sS][yY][sS][aA][lL][iI][vV][eE]([[:space:]]|$)/{print $0,++cnt;next}1' file.txt > file2.txt

If you just want the 6th field or just want the last field, you can simplify it a little bit, but you can still use the same general structure.

awk '{printf("%s%s\n",$0,tolower($NF)=="sysalive"?" "++c:"")}' file