sed - convert regex pattern matches to lowercase #

In this example, we'll convert text within bold tags to lowercase. Let's have a look first to make sure our search pattern returns the desired results:
$ grep '<b>.*<\/b>' foo.html
<p><a href="/">tinyapps.org</a> / <b>Graphics</b></p>
<p><b>Viewing & Editing</b></p>
<p><b>Measuring</b></p>
<p><b>Optimizing</b></p>
<p><b>Screen Capture</b></p>
<p><b>Fonts</b></p>
<p><b>Other</b></p>
Next, a test run, sending output to stdout:
$ sed 's/<b>.*</b>/\L&/g' foo.html
As expected, all characters between bold tags were converted to lowercase. (In the replacement pattern, "&" corresponds to the pattern found, and "\L" converts the text to lowercase.) Now let's use -i to write the changes in place (apparently introduced around GNU sed version 4):
$ sed -i 's/<b>.*</b>/\L&/g' foo.html
For batch processing multiple files:
$ grep '<b>.*<\/b>' *.html
...
$ for i in '*.html'; do sed -i "s/<b>.*</b>/\L&/g" $i; done
Two related tips by Karoly: 1. Use double quotes so the shell can substitute variables. 2. If your search or replace string contains special characters you need to escape them.

/nix | May 19, 2013


Subscribe or visit the archives.