Operating System - HP-UX
1837976 Members
2768 Online
110124 Solutions
New Discussion

Re: How to find and replace a string within a text file

 
Randy Hagedorn
Regular Advisor

How to find and replace a string within a text file

Hi everyone,

I have an application where I want to execute a script that searches a file for a specific string and replace it with another string value.

Can anyone tell me how to do this?

Thanks,
Randy
3 REPLIES 3
Randy Hagedorn
Regular Advisor

Re: How to find and replace a string within a text file

Addendum,

I probably should add that I want to do this with HP-UX.

Randy
Pete Randall
Outstanding Contributor

Re: How to find and replace a string within a text file

Randy,

Use sed:

sed 's|string1|string2|g'


Pete

Pete
A. Clay Stephenson
Acclaimed Contributor

Re: How to find and replace a string within a text file

Probably the best way to do this (and avoid the use of a temporary file plus a mv that both sed and awk would require) is perl with the -i and -pe switches. This will edit a file in place.

perl -i -pe 's/oldstuff/NewStuff/g' myfile

Be warned that there is no safe copy so get your syntax correct on play files before turning it loose on production.

If you use -i.saf (or -i.anysuffix) rather than simply "-i" a backup copy (e.g. myfile.saf') will be created while editing the original myfile.
If it ain't broke, I can fix that.