Make multiple edits with a single call to sed

You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file).

sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file, in-place. Without a backup file.

sed -ibak -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file, in-place. With a single backup file named filebak.


As well as using multiple -e options, you can also separate sed commands in a single sed script using newlines or semi-colons.

This is the case whether that script is a one-liner on the command line, or a script file.

e.g.

sed -e 's/a/b/g ; s/b/d/g' file

The space characters around the ; are optional. I've used them here to make sure the semi-colon stands out (in general, except for newlines separating commands, white-space between commands is ignored...but don't forget that white space within commands can be and usually is significant).

or:

sed -e 's/a/b/g
        s/b/d/g' file

Another alternative is ex, the predecessor to vi. It is actually the POSIX tool of choice for in-place scripted file editing; it is extraordinarily more flexible than sed -i and arguably even more portable than Perl. (If you stay outside of the Windows world, it's unarguably more portable than Perl.)

There is a relative dearth on this stackexchange of example commands using ex, at least compared with the plethora of example commands using sed, awk and Perl. However, I myself have delved extensively into the POSIX specs for ex and I've been beating the drum for it ever since. I've written many answers using ex both here and on the vi/Vim stackexchange:

  • Delete 4 line above and below 5 line after pattern match
  • How to delete everything after a certain pattern or a string in a file?
  • grep all the lines in a file and write line to a file from the pattern matching point
  • How can I replace a character in all the .php files inside a folder on OS X?
  • How to append some line at the end of the file only if it's not there yet?

Further reading:

  • Does Ex mode have any practical use?
  • How to edit files non-interactively (e.g. in pipeline)?

Tags:

Sed