1

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"

3 Answers 3

4

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"
Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

sed has the ability to edit files in place without the need to make temp files by hand.
Instead of 3 commands and a temp file sed -i "s/$2/$3/g" $1 will work just fine.
@yan Neat, I didn't know that :-)
@Johnathan: edit and save only by combining both sed options, like : sed -i -e "s/foo/bar/g" my_file
0

Ruby(1.9+)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.