Solved

Replace n Occurrence using Awk

Posted on 2013-05-09
1
308 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 53

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

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

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

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…
Join Greg Farro and Ethan Banks from Packet Pushers (http://packetpushers.net/podcast/podcasts/pq-show-93-smart-network-monitoring-paessler-sponsored/) and Greg Ross from Paessler (https://www.paessler.com/prtg) for a discussion about smart network …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

770 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