So I want to create a script that takes 3 arguments - path to file, exact word to replace and with what to replace it. How to create such thing?
Generally I want6 it to have api like sudo script.sh "C:/myTextDoc.xml" "_WORD_TO_REPLACE_" "WordTo Use"
You don't need a script, a simple sed would do (if you're running under cygwin or a POSIX-compliant OS):
sed -i '' 's/_WORD_TO_REPLACE_/WordTo Use/' "C:/myTextDoc.xml"
Something like this?
#!/bin/bash
sed -e "s/$2/$3/g" <$1 >$1.$$ && cp $1.$$ $1 && rm $1.$$
Alternatively, you can use the single command
sed -i -e "s/$2/$3/g" $1
as Yan suggested. I generally use the first form myself. I have seen systems where -i
is 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
Ruby(1.9+)
$ ruby -i.bak -ne 'print $_.gsub(/WORD_TO_REPLACE/,"New Word")' /path/to/file