How to replace text in a text file using a .SH script file?

So, I want to create a script that takes 3 arguments - the path to the file, the exact word to replace and with what to replace it. How to create such a thing?

Generally, I want6 to have api as sudo script.sh "C:/myTextDoc.xml" "_WORD_TO_REPLACE_" "WordTo Use"

0
source share
3 answers

You do not need a script, a simple sed (if you are running cygwin or a POSIX-compatible OS):

 sed -i '' 's/_WORD_TO_REPLACE_/WordTo Use/' "C:/myTextDoc.xml" 
+4
source

Something like that?

 #!/bin/bash sed -e "s/$2/$3/g" <$1 >$1.$$ && cp $1.$$ $1 && rm $1.$$ 

Alternatively you can use a single command

 sed -i -e "s/$2/$3/g" $1 

as Ian suggested. I usually use the first form. I have seen systems where -i not supported (SunOS).

This will replace all instances of the second argument with the third, in the file passed as the first. For example, ./replace file oldword newword

+2
source

Ruby (1.9 +)

 $ ruby -i.bak -ne 'print $_.gsub(/WORD_TO_REPLACE/,"New Word")' /path/to/file 
0
source

All Articles