At work, I’ve been more than once exposed to older web sites that had to be changed. Problematic about this was, that I would have to edit about 30 html files to change an email address or change a part of the menu that was stored on every single html page. As I thought, that this was far too annoaying, I decided to write a script for it.
The stream editor (sed) that is pretty much standard on basically every distribution and a core element offers the search and replace function, but I will stop to annoy you and just give you the script:
#!/bin/bash # a little help by Jonathan M. Hethey # use: # 1. put in directory with files to edit # 2. change variables replace and with # declare the variable you want to have replaced replace="old_pic.png" # and the string you want to replace it with with="new_pic.png" # the script will do it on all files with a certain file suffix, .html in this case for filename in *.html # loop it for all files found with .html do # search and replace it sed -i "s/$replace/$with/g" $filename # echo all files processed, this gives you information which files were worked on (probably all .html files, because sed will read all, but only work on the ones where there is something to be replaced. echo $filename # end the loop done;
A little struggle was to get the variables (I only added for you, my readers) to work. It’s all about using ” instead of ‘ because bash does not interpret variables inside ‘.