Operating System - HP-UX
1827813 Members
1965 Online
109969 Solutions
New Discussion

Replacing strings in a file at certain line numbers?

 
SOLVED
Go to solution
Russ Hancock_1
Frequent Advisor

Replacing strings in a file at certain line numbers?

Does anyone know a command(s) that will replace a given string at specific line numbers throughout a file?

For example, I need to replace string '123' with '456' but only at the lines 10, 15 and 40, no where else in the file?

Any ideas?

Cheers
Russ.
Russ
4 REPLIES 4
Ravi_8
Honored Contributor

Re: Replacing strings in a file at certain line numbers?

Hi Russ

This can be done throughout the file using sed
(sed s/123/456/g file_name), but at specific line numbers is quite difficult, let me try and come back to you.
never give up
James R. Ferguson
Acclaimed Contributor
Solution

Re: Replacing strings in a file at certain line numbers?

Hi Russ:

Try this:

# for X in 10 15 40
> do
> sed -e $X's/old/new/' filein > fileout
> mv fileout filein
> done

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: Replacing strings in a file at certain line numbers?

Hi (again) Russ:

If you have multiple occurances of the "old" string that you want substituted by the "new" string on a line, add the 'g' flag for global replacement. Otherwise, only the first occurance per line will be replaced (substituted).

sed -e $X's/old/new/g' filein > fileout

Regards!

...JRF...
Mark Greene_1
Honored Contributor

Re: Replacing strings in a file at certain line numbers?

You can do this with sed:

sed -n 's/123/456/,10p'
sed -n 's/123/456/,15p'
sed -n 's/123/456/,40p'

if you wanted to do lines 15 THROUGH 40, it would be like this:

sed -n 's/123/456/,15,40p'

HTH
mark
the future will be a lot like now, only later