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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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

Method 3

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:

Further reading:


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x