Operating System - HP-UX
1827293 Members
3514 Online
109717 Solutions
New Discussion

Re: replacing just one specific occurance in file

 
SOLVED
Go to solution
Bill McNAMARA_1
Honored Contributor

replacing just one specific occurance in file

If following is my file,
how do I replace just the first LPC=10 to LPC=40
and not the second or further occurances?

Thanks,
Bill!

[ Isup_SS7_Platform ]
LPC=10, classname=SS7_Stack_1, MtpProtocol=ITU, IsupProtocol=ITU

[Isup_Dpc_10_20]
LPC=10
DPC=20
~
~
~
It works for me (tm)
8 REPLIES 8
Bill McNAMARA_1
Honored Contributor

Re: replacing just one specific occurance in file

The 40 can come from
a: specific change
b: adding 30

It's possibly better to just change to
LPC=101
by adding a 1 to the end of what's in the file originally and the format can be different.. ie not always a decimal number.

Thanks,
Bill
It works for me (tm)
Steven Sim Kok Leong
Honored Contributor

Re: replacing just one specific occurance in file

Hi Bill,

# cat file | sed -e 's/LPC=10,/LPC=40,/'

I know I am cheating but hey, it works :P

Hope this helps. Regards.

Steven Sim Kok Leong
Steven Sim Kok Leong
Honored Contributor

Re: replacing just one specific occurance in file

Hi Bill,

Forgot to add, try using the comma (,) to advantage.

Hope this helps. Regards.

Steven Sim Kok Leong
Bill McNAMARA_1
Honored Contributor

Re: replacing just one specific occurance in file

That changes the second occurance also.. I though it did that just with the g ..?

/usr/bin/sed -e "s|^$key=$LPC|$key=$value|" $filename > $TMP_WORKFILE

where key=LPC
LPC=10
value=${LPC}1

Later,
Bill
It works for me (tm)
Robin Wakefield
Honored Contributor
Solution

Re: replacing just one specific occurance in file

Hi Bill,

Try:

/usr/bin/sed -e "1,/$LPC/s|^$key=$LPC|$key=$value|" $filename > $TMP_WORKFILE

This will stop replacing once it's found the 1st occurrence.

The g switch is for replacing all occurrences in *each* line.

Rgds, Robin.
Bill McNAMARA_1
Honored Contributor

Re: replacing just one specific occurance in file

thats for clearing that up Robin!

(Back into a scripting week, hope the forums stay online!)

Later,
Bill
It works for me (tm)
Steven Sim Kok Leong
Honored Contributor

Re: replacing just one specific occurance in file

Hi Bill,

Using the sample you provided, only the first occurrence of LPC=10 has a comma after it. Thus, using the comma will work for your sample above.

However from your response, I gather that the second occurrence of LPC=10 in your full text actually has a comma tagging after it. If that is the case, then using the comma to differentiate the first occurrence from the rest in my method will not work.

Hope this helps. Regards.

Steven Sim Kok Leong
Bill McNAMARA_1
Honored Contributor

Re: replacing just one specific occurance in file

Right on Steven,

That works fine too.

Later,
Bill
It works for me (tm)