Solved

Replace n Occurrence using Awk

Posted on 2013-05-09
1
310 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 54

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 Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Setting up Secure Ubuntu server on VMware 1.      Insert the Ubuntu Server distribution CD or attach the ISO of the CD which is in the “Datastore”. Note that it is important to install the x64 edition on servers, not the X86 editions. 2.      Power on th…
Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

713 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