Ideally, this should be done in a language like perl
or python
which have good HTML parsing libraries. But if you want to do it in a shell script, you can install the xml2 package, which provides tools called html2
and 2html
for converting HTML to and from a flat-file format suitable for use with line-oriented tools like sed
, grep
, awk
, etc.
It also contains similar tools for working with XML and CSV files.
Then you can use sed
to transform spaces on matching img src
lines to dashes. Then convert back to html.
For example, using your sample html line:
$ cat file.html
<img class="photo" width="400" height="600" src="/images/red roses in summer 54.jpg" alt="">
$ html2 < file.html | sed -e '\:/img/@src=/images/: s/ /-/g' | 2html
<html><body><img class="photo" width="400" height="600" src="/images/red-roses-in-summer-54.jpg" alt="">
Redirect the output from that to, e.g., file.new.html
. and then mv -f file.new.html file.html
if you want to replace the original file with the modified version. I very strongly recommend keeping a backup copy of the original files so that you can revert to a known-good starting point if you make a mistake.
BTW, the flat-file format produced by html2
looks like this:
$ html2 < file.html
/html/body/img/@class=photo
/html/body/img/@width=400
/html/body/img/@height=600
/html/body/img/@src=/images/red roses in summer 54.jpg
/html/body/img/@alt
xml2
is packaged for Debian and Ubuntu and probably other Linux distros. If it's not available pre-packaged for your unix, you can find the source code at the link above.
There are many ways to make these changes in lots of files. Here's a simple for
loop example.
for htmlfile in *.html ; do
html2 < "$htmlfile" |
sed -e '\:/img/@src=/images/: s/ /-/g' |
2html > "$htmlfile.new" \
&& mv -f "$htmlfile.new" "$htmlfile"
done
WARNING: test that this does what you expect before running it on lots of HTML files. And keep a backup of the originals. If the HTML in your files is not completely valid HTML (i.e. if it won't pass a HTML syntax checker) then html2 | ... | 2html
could make your html files even more broken than they already are.
If there are too many files, or the files are in multiple subdirectories, you'll have to use find ... -exec
. There are countless examples of using find
here on this site.