Solved

Replace n Occurrence using Awk

Posted on 2013-05-09
1
311 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 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 learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

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

Suggested Solutions

SSH (Secure Shell) - Tips and Tricks As you all know SSH(Secure Shell) is a network protocol, which we use to access/transfer files securely between two networked devices. SSH was actually designed as a replacement for insecure protocols that sen…
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 the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

752 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