# Make multiple edits with a single call to sed

I'm trying to use sed to edit a config file. There are a few lines I'd like to change. I know that under Linux sed -i allows for in place edits but it requires you save to a backup file. However I would like to avoid having multiple backup files and make all my in place changes at once.

Is there a way to do so with sed -i or is there a better alternative?

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.

• Note that the sequence matters. In the example command given above, all instances of the letter a are turned into b, and then all instances of b are turned into d. You could do the same thing with sed -i -e 's/a\|b/d/g' file—turn all instances of either a or b into d. – Wildcard Mar 11 '16 at 1:53

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: