INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Increment Replacement With Starting Value

Increment Replacement With Starting Value

(OP)
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

RE: Increment Replacement With Starting Value

2
Hi

Then do not increment it before the substitution :

CODE --> Awk

sub(/xx/,c++) 

But note that Awk does not support code in the substitution :

CODE --> command line

master # 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

RE: Increment Replacement With Starting Value

(OP)
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 smile

RE: Increment Replacement With Starting Value

Hello,

Following may too help for same.

CODE

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


Thanks,
R. Singh


Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close