Solved

Replace n Occurrence using Awk

Posted on 2013-05-09
1
306 Views
Last Modified: 2013-05-09
Input: peter peter tom
Output: peter chris tom

-----------------------

I'd like to replace the 2nd occurrence of a string using awk.

-----------------------

I know this can easily be done with sed, but I'm trying to learn awk.

-----------------------

I tried this, but it's not working:

echo peter peter tom | awk '{ c++; if(c==2) { sub( "peter", "chris" ); c=0; print } }'

Open in new window


-----------------------

Any help is appreciated.
0
Comment
Question by:Neapolitan23
1 Comment
 
LVL 51

Accepted Solution

by:
Bill Prew earned 500 total points
ID: 39154163
Try this:

{ c = 0; for (i = 0; ++i <= NF;) { if( $i == "peter" ) { c++; if( c == 2 ) { $i = "chris" } } }; print $0 }

Open in new window

~bp
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

It is a general practice to get rid of old user profiles on a computer  in a LAN environment. As I have been working with a company in a LAN environment where users move from one place to some other place at times. This will make many user profil…
Introduction We as admins face situation where we need to redirect websites to another. This may be required as a part of an upgrade keeping the old URL but website should be served from new URL. This document would brief you on different ways ca…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now