Gary Sieling

Replace in files recursively with sed

Replacing text in many files is reasonably simple with sed, on the command line.

If you do this, I would recommend that you come up with a way to take a backup, because there is almost no chance you’ll get it right on the first try.

My preferred approach is to make an empty git repository with the initial state, which allows me to rollback the changes every time I need to iterate on the sed script.

git init .
git add -A 
git commit -m "files"

For this example, I’m adding an Amazon link to a bunch of files. The successful solution is as follows (you want the generate format of “s///” to control it in your own script).

find . -type f -iname '*.html' -exec sed -i 's/"sidebar-module">/"sidebar-module">

Once you create this script, you should check it in.

...add script...
git add replace.sh
git commit -m "script"

I found there were several problems getting this to work. You need to escape & and \, and make sure to replace what you removed – it’s often helpful to use a chunk of text that comes before or after the replacement.

When you make a mistake, you can just do

git reset --hard

As long as you’re committing the replacement script as you go.

If you like, you can get rid of the git repository once you’re done, by doing this:

rm -rf .git

~

Exit mobile version