Run sed over multiple files

To run a sed command over multiple files in a directory.

For example, to modify the .htm files in a directory, outputting the changed files to a subdirectory called output/, use:

ls -1 *.htm | { while read i; do sed -f modify.sed $i > output/$i; done }

This pipes the output of a single column ls command (-1 is the numeral one) of *.htm files into a while loop that acts on each line of the ls command's output.

Each iteration of the loop runs the sed command using the modify.sed file that contains the modification commands. Which might have:

s|<b>|<strong>|g;
s|</b>|</strong>|g;

Which changes the bold tag to the strong tag. Using | as the delimiter to avoid the \/\/\\/ nightmare. :)

The output of the sed command is redirected to the same filename as the input file, but into a subdirectory called output/ which has to exist.

Back to GNU/Linux Command Line Tips