1838373 Members
3212 Online
110125 Solutions
New Discussion

Re: Global Substitution

 
Global Server Operation
Frequent Advisor

Global Substitution

Anyone know how to do global substitution on a file? I 'm in a time crunch and need to know. I'm not too familiar with this command.
3 REPLIES 3
Yang Qin_1
Honored Contributor

Re: Global Substitution

Hi, if you use vi to edit the file then:
press Esc --> : --> %s/keyword/replacement/g --> w (save) --> q (quit)

If you use "sed":
sed 's/keyword/replacement/g' file1 > file2


Yang
James R. Ferguson
Acclaimed Contributor

Re: Global Substitution

Hi:

While 'sed' is certainly one, common choice, you must redirect its output to a different file than its input and then move ('mv') the output over the input afterwards.

Perl allows inplace substitution, and optionally the retention of the original file as a backup copy.

# perl -pi.old -e 's/\bOLD\b/NEW/gi' file

The "\b" is a "boundry" so that OLD is replaced by NEW but not OLDER.

The '-i' switch causes replacement to be case insensitive. Here, "Old", "OLD", "olD" are all treated the same and would be replaced with "NEW".

The '-pi.old' tells Perl to print and perform an inplace edit, first preserving a a copy of 'file' as 'file.old'. If you don't want a backup copy of the original file, simply use '-p' instead.

As you can see, Perl's substitution syntax is similar to 'sed'.

Regards!

...JRF...



Igor Sovin
Super Advisor

Re: Global Substitution

Hi!

Another way in Vi:
also press Esc, then
:1,$s/statement/subst/g