Computing.Net > Forums > Unix > replace in sed

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 in sed

Reply to Message Icon

Name: arulactive
Date: September 30, 2009 at 01:38:41 Pacific
OS: Windows Vista
CPU/Ram: 12
Product: Sun microsystems Solms-251wd999 2.5.1
Subcategory: General
Tags: solaris
Comment:

I'm using sed.i.e search for pattern and then do the replace. I want to replace 5657 with 10000
in lines which have the pattern /xyz/data. I will be passing env variables to sed and I tried the
following but doesn't work. Can some one help me on this?
$cat file123
/xyz/data01,1234
/xyz/data02,1234
/xyz/data,5657
$export FX str str2
$echo $FS $str $str2
/xyz/data 5657 100000
$sed "/$FX/s/$str/$str2/g" file123
First RE may not be null
$sed "%$FX%s%$str%$str2%g" file123
Unrecognized command: %/xyz/data%s%5657%100000%g
$



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: September 30, 2009 at 21:27:58 Pacific
Reply:

This is a tricky one. First, if the shell variable to be embedded in the sed script contains a front slash, it must be escaped \/

FX="\/xyz\/data"

Second, the RE must be surrounded by / /

Third, note that I included a caret character, ^, at the beginning of the character so only lines in the file starting with:

/xyz/data

are modified.


#!/bin/ksh

FX="\/xyz\/data"
str=5657
str2=10000
sed "/^${FX}/s!${str}!${str2}!g" file123


1

Response Number 2
Name: arulactive
Date: October 1, 2009 at 12:49:24 Pacific
Reply:

Hi nails,

Ah!. You have rescued me again. Thanks nails.
The solution worked well.


0

Response Number 3
Name: ghostdog
Date: October 2, 2009 at 23:57:18 Pacific
Reply:

use awk

#!/bin/bash
FX="\/xyz\/data"
str=5657
str2=10000
awk -v str=$str -v str2=$str2 '/xyz/{gsub(str,str2)}1' file

GNU win32 packages | Gawk


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More






Use following form to reply to current message:

Login or Register to Reply
LoginRegister


Sponsored links

Ads by Google


Results for: replace in sed

parameters in sed www.computing.net/answers/unix/parameters-in-sed/6942.html

parameters to sed doesnt work www.computing.net/answers/unix/parameters-to-sed-doesnt-work/7467.html

How to use if/else logic in sed/awk www.computing.net/answers/unix/how-to-use-ifelse-logic-in-sedawk/6207.html