sed with multiple expression for in-place argument

I am trying to replace multiple words in a file by using

sed -i #expression1 #expression2

file

Something  123 item1
Something  456 item2
Something  768 item3
Something  353 item4

Output (Desired)

anything  123 stuff1
anything  456 stuff2
anything  768 stuff3
anything  353 stuff4

Try-outs

I can get the following output by using sed -i two times.

 sed -i 's/Some/any/g' file
 sed -i 's/item/stuff/g' file

Can I have any possible way of making this as a single in-place command like

sed -i 's/Some/any/g' -i 's/item/stuff/g' file

When I tried the above code it takes s/item/stuff/g as a file and tries working on it.

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

Depending on the version of sed on your system you may be able to do

sed -i 's/Some/any/; s/item/stuff/' file

You don’t need the g after the final slash in the s command here, since you’re only doing one replacement per line.

Alternatively:

sed -i -e 's/Some/any/' -e 's/item/stuff/' file

Or:

sed -i '
  s/Some/any/
  s/item/stuff/' file

The -i option (a GNU extension now supported by a few other implementations though some need -i '' instead) tells sed to edit files in place; if there are characters immediately after the -i then sed makes a backup of the original file and uses those characters as the backup file’s extension. Eg,

sed -i.bak 's/Some/any/; s/item/stuff/' file

or

sed -i'.bak' 's/Some/any/; s/item/stuff/' file

will modify file, saving the original to file.bak.

Of course, on a Unix (or Unix-like) system, we normally use ‘~’ rather than ‘.bak’, so

sed -i~ 's/Some/any/;s/item/stuff/' file

Method 2

You can chain sed expressions together with “;”

%sed -i 's/Some/any/g;s/item/stuff/g' file1
%cat file1
anything  123 stuff1
anything  456 stuff2
anything  768 stuff3
anything  353 stuff4

Method 3

Multiple expression using multiple -e options:

sed -i.bk -e 's/Some/any/g' -e 's/item/stuff/g' file

or you can use just one:

sed -i.bk -e 's/Some/any/g;s/item/stuff/g' file

You should give an extension for backup file, since when some implementation of sed, like OSX sed does not work with empty extension (You must use sed -i '' to override the original files).

Method 4

You can use Vim in Ex mode:

ex -sc '%s/Some/any/|%s/item/stuff/|x' file
  1. % select all lines
  2. s substitute
  3. x save and close


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