Computing.Net > Forums > Unix > replace text

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

replace text

Reply to Message Icon

Name: deep.singh
Date: May 31, 2005 at 07:44:21 Pacific
OS: HP-UX 11.11
CPU/Ram: 4
Comment:


I have i/p file with following text -->
456 StreetA Rd (702) 456-7890
123 StreetB Rd 345-5678
789 StreetC Rd 123-8765
356 StreetD Rd (702) 657-3456


I want o/p file like below -->
456 StreetA Rd (702) 456-7890
123 StreetB Rd (702) 345-5678
789 StreetC Rd (702) 123-8765
356 StreetD Rd (702) 657-3456

Basically If text "(702)" is missing in each line, then i want to append (702) after text 'Rd '



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: May 31, 2005 at 08:40:47 Pacific
Reply:

Provided your data file follows the structure you laid out this should work. I'm using Solaris, so I'm using nawk. You'll probably have to change that to awk:


#!/bin/ksh

nawk ' BEGIN { ck_str="(702)" } {
if ($4 != ck_str)
{
$5=$4
$4=ck_str
}
print $0
} ' data.file



0

Response Number 2
Name: Jim Boothe
Date: May 31, 2005 at 08:48:11 Pacific
Reply:

This first solution targets only lines that do not contain (702), and changes the first occurrence (if any) of Rd in each of these lines to Rd (702) regardless of what follows Rd - but we know it will not be (702):

sed '/(702)/!s/Rd/Rd (702)/'


This second solution searches for the first occurrence in each line of Rd where Rd is delimited by single spaces and followed by any character that is not a left parenthesis.  If found, it changes Rd to Rd (702).  In other words, if Rd is already followed by a parenthesis, it leaves it as is.

sed 's/ Rd \([^(]\)/ Rd (702) \1/'


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: replace text

Unix replacing text www.computing.net/answers/unix/unix-replacing-text/7215.html

Replace Text www.computing.net/answers/unix/replace-text/6940.html

Adding variable at end of the row www.computing.net/answers/unix/adding-variable-at-end-of-the-row/7466.html