-   Linux - Newbie (
-   -   SED - substitute a word only in a certain line (

carolflb 02-02-2010 10:01 AM

SED - substitute a word only in a certain line
Hi everybody,

I tried to use the command:

sed -i ''$line_number',/port/s/port/portMARKED/' file

to substitute the word "port" by the word "portMARKED" at the specific line that is saved in "line_number". The substitution happens, but it is copying my line twice... and I have no idea why...

I need to make a single substitution of one word for another at a certain line in my text file. Would somebody know how I could do that?


druuna 02-02-2010 10:20 AM


sed "${line_number}s/port/portMARKED/" infile

I'm not sure why you added the ,/port/ part, it is not needed.

General form (substitute with address range): sed '[address1[,address2]]s/pattern/replacement/[flags]' infile

flags is not used in your example, but could be g (global replace on whole line).

Hope this helps.

amon 02-02-2010 10:27 AM

Some handy sed examples:

From that link:

# substitute (find and replace) "foo" with "bar" on each line
 sed 's/foo/bar/'            # replaces only 1st instance in a line
 sed 's/foo/bar/4'            # replaces only 4th instance in a line
 sed 's/foo/bar/g'            # replaces ALL instances in a line

you have already seen the use of the

option for inserting text to the file.
Not sure what the other parts were (or if you had got confused with the sed instructions as I often do).

if I take file (tmptxt.txt):

text1 text text
text2 text text
text3 text3 text3

And run:

sed -i '2 s/text/textMARKED/' tmptxt.txt
I get:

text1 text text
textMARKED2 text text
text3 text3 text3

in your script you may need to replace single quotes with double quotes.

carolflb 02-02-2010 10:30 AM

Thanks a lot guys!

I saw the comma in another example, but now I understood why it should not be there.

All times are GMT -5. The time now is 05:09 AM.