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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Increment Replacement With Starting Value 2

Status
Not open for further replies.

JBorges

Technical User
Jan 12, 2009
57
DK
Hello.

How do I find and replace a string with a specific starting value?

I have this text:
xx
xx
xx

and would like to replace it with:
0
1
2

My awk code is contained in my regex.awk file and run from my Mac's Terminal. This code works fine but it starts replacement at value '1' and I want it to be '0'. I've search the forum but couldn't an answer.
awk:
sub(/xx/,++c)

Terminal:
awk -f awkRegex.awk test.txt > test.tmp && mv test.tmp test.txt
 
Hi

Then do not increment it before the substitution :
Code:
sub(/xx/,c++)

But note that Awk does not support code in the substitution :
Code:
[blue]master #[/blue] awk '{sub(/xx/,c++)}1' <<< $'xx\nyy\nxx\nzz\nxx'
0
yy
2
zz
4
As you can see, the code is just executed, actually is unrelated to the substitution.

Such code like your attempt would work in Perl, Ruby, Python, PHP, JavaScript and other languages where code is allowed in the substitution. But in Awk you will need different strategy.

Feherke.
feherke.ga
 
Excellent! Thanks a lot.

As simple as moving the 'c' before the '+' signs. Can't help laughing at myself that it was so unbelievably simple :)
 
Hello,

Following may too help for same.

Code:
awk 'gsub(/xx/,(NR-1))1' file_name


Thanks,
R. Singh


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top