Pattern search and modify the values

I have one file and the file may contain 500 to 15,000 records. I need to search pattern ^F509= and then increment the corresponding value by one and print the entire line.
Please note that Its not a fixed length file. Can anyone please help?

ex:

^F509=204656
     ^F509=204656
     ^F509=204656

The value should be

^F509=204656
                              ^F509=204657
                              ^F509=204658

Please refer the attached input and output file.

What if that field's numbers are NOT equal?

^F509=204656
^F509=209996
^F509=146569

Try something like:

awk '$2~/^F509=/{split($2,F,/=/); if(n=="")n=F[2]; $2=F[1]"="n++}1' FS=^ OFS=^ file

The field numbers are always equal.

---------- Post updated at 03:12 PM ---------- Previous update was at 03:10 PM ----------

I'm not sure whether this logic will work because ^F509 can come anywhere in the file (not $2) .

Try

awk 'match ($0, /\^F509[^^]*/) && !L {L=1; m=n=substr ($0, RSTART+6, RLENGTH-6)} {sub (m, n++)}1' /tmp/inputfile.txt
DATAk(jdkfjk)09335"mk"8789eetet8766^F509=204657^F321=khfjfd^F870=76547854
DATAk(jdkfjk)09335"mk"8789rtrtr87f6^F509=204658^F321=khfdfdf^F870=76547854
DATAk(jdkfjk)09335"mk"878dg98fdd766^F509=204659^F321=khddjfd^F870=76547854
1 Like

Ok, adjusted to any field:

awk '{for(i=1; i<=NF; i++) if($i~/^F509=/){split($i,F,/=/); if(n=="")n=F[2]; $i=F[1]"="n++}}1' FS=^ OFS=^ file

---

This will fail if there is a line that happens to have the same sequence of numbers before the F509 field. Then sub (m, n++) will substitute those numbers instead of those in the F509 field...

1 Like

Hello Forum!

Back after a long absence. Awk is fun and I needed to flex my brain cells. Here is mine:

awk '$2~/^F509/{i++; split($2,a,"="); $2=a[1]"="a[2]+i}1' FS=^ OFS=^ file