Linux sed command - modify the content of many files

Linux sed FAQ: How can I use the sed command to modify many files at one time?

Here's a Linux/Unix sed command file that I just used to modify a bunch of files:

s/^M//g
1,2d
$d

I put those three lines in a text file, and named the file sed.cmds.

After that, I call that sed script from a simple shell script. Here are the contents of the shell script:

#!/bin/sh

# modify every *.txt file in the current directory
for i in `ls *txt`
do
  sed -f sed.cmds < $i > ${i}.new
done

What I'm doing in this shell script is:

  1. Getting a list of all files in the current directory that end with the extension "txt".
  2. Running my sed command on each file, reading from the original file ($i), and writing to a new file, where the extension ".new" is appended to the end of the original filename.
  3. Note that I'm reading the sed command file by using the "-f sed.cmds" argument to the sed interpreter.

Nothing too exciting here, but it is incredibly productive, and I don't want to forget how I did this.

Also note that you can rename your ".new" files back to ".txt" files with a mv command, but I'll leave that as an exercise for the reader, especially because that command will overwrite your original .txt files, and I don't want anyone blaming me for that. :)

Post new comment

The content of this field is kept private and will not be shown publicly.