Solved

Replace n Occurrence using Awk

Posted on 2013-05-09
1
312 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 56

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Background Still having to process all these year-end "csv" files received from all these sources (including Government entities), sometimes we have the need to examine the contents due to data error, etc... As a "Unix" shop, our only readily …
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

635 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