Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK Search and replace with count 1

Status
Not open for further replies.

dbehera

Programmer
May 31, 2005
8
US
I am new to awk and I have a FIXML file that I want to search a string and replace with a counter. Here is the file.

<FIXML> <TrdCaptRpt AvgPxInd="1" RptID="40104" LastQty="15" LastPx="2910" TrdDt="2005-04-19" TxnTm="2005-05-17T10:30:00" TransTyp="0" RptTyp="0" </FIXML> <FIXML> <TrdCaptRpt LinkID="GRPGRPID" AvgPxInd="1" RptID="40104" LastQty="15" LastPx="2910" TrdDt="2005-04-19" TxnTm="2005-05-17T10:30:00" TransTyp="0" RptTyp="0" </FIXML>

I have a huge file and want to replace it with incrementing counter at the LinkID="GRPGRPID" as LinkID="GRP1" and LinkID="GRP2" and so on.

Is it possible to use awk and sed to achieve it. Thanks for the help.
 
Code:
{ gsub(/LinkID="GRPGRPID"/, "/LinkID=\"GRP" ++cnt "\"") }
1

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Maybe this is safer:
Code:
{ while($0~/LinkID="GRPGRPID"/)
    sub(/LinkID="GRPGRPID"/,"LinkID=\"GRP" ++cnt "\"")
  print
}

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
The while loop actually works better. Thanks guys. I was trying to use a sed in a awk and did not work.
 
hmmm..... just wondering why 'while' is better/safer?


vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
why 'while' is better/safer?
Because most awk evaluate ++cnt once for each gsub call.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
ah....... got it!
mucho thanks!

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
BEGIN { cnt = 1 }
{ while (sub(/LinkID="GRPGRPID"/, "LinkID=\"GRP" cnt "\""))
cnt++
print
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top