Operating System - Linux
1752774 Members
4882 Online
108789 Solutions
New Discussion юеВ

Re: change a line in a file

 
SOLVED
Go to solution
Anand_30
Regular Advisor

change a line in a file

Hi,

I have migrated some web application from one server to a new server.

Now I have around 150 html files in which I have to change the server names.

I know that I can use 'sed' to do it without opening the file but I will have to create a new file everytime I make change to an existing file.

Can anyone please tell me a more suitable way to perform the changes in the file.

Thanks,
Anand
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

Re: change a line in a file

Hi Anand:

Use perl and do in-place modification:

# perl -i.old -pe 's/oldname/newname/g' file1 file2 ...

If you don't want to preseve a pre-modified copy, do:

# perl -i -pe 's/oldname/newname/g' file1 file2 ...

That is, simply drop the argument (for example ".old") following the '-i' option.

Multiple files can be specified at once as noted.

Regards!

...JRF...



Jeff_Traigle
Honored Contributor

Re: change a line in a file

You can use ex to edit them in place.

for FILE in list_of_files
do
ex ${FILE} <1,$s/oldhostname/newhostname/g
wq!
EOD
done

(I think I remember the syntax of the substitution, but you might want to test it to be sure.)
--
Jeff Traigle
Peter Nikitka
Honored Contributor

Re: change a line in a file

Hi,

in this cases I generate ed-commands to do this.
Note1: Backup the files before you try!
Note2: use your appropriate method of getting the filenames
Note3: better tighten the pattern used for the global match (2nd print statement)

oldserver=XXX
newseerver=YYY
for f in $(fgrep -l $oldserver *.html)
do
print f $f
print g/$oldserver/s/$oldserver/$newserver/g
print w
done | ed

to review the ed-commands use this last line:
...
done >/tmp/ed.cmd

and then execute them via

ed
Use 'ed -s' istead of 'ed' to suppress ed-output.

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Peter Nikitka
Honored Contributor

Re: change a line in a file

Hi,

typo - change
for f in $(fgrep -l $oldserver *.html)
do
print f $f

to

print e $f

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Arturo Galbiati
Esteemed Contributor

Re: change a line in a file

Hi,
I use the ChanheSTring.ksh attched to perofrm this. It makes a backup copy of teh files changed and show you the line changed.
I love it.
HTH,
Art