tabs_over_spaces
tabs_over_spaces

Reputation: 362

Use sed to insert another sed command in a file

I am trying to use sed to insert sed command at the end of each line in a file using -

sed -r 's/$/ | sed -r s\/abc\/xyz\/ /' filename.extension

What I want next is to have single quotes around the inner sed. So that it will look something like-

sed -r 's/$/ | sed -r 's\/abc\/xyz\/' /' filename.extension

I tried escaping the inner single quotes, but no use.

Basically, I want the following lines -

line 1 line 2 line 3

to turn into-

line 1 | sed -r 's/abc/xyz/' line 2 | sed -r 's/abc/xyz/' line 3 | sed -r 's/abc/xyz/'

I am unable to get the single quotes, even with the escape characters.

Upvotes: 0

Views: 2383

Answers (3)

DigitalRoss
DigitalRoss

Reputation: 146281

sed -e "s:$: | sed -r 's/abc/xyz/':" yourfile

Your problem is an example of the general case of nesting shell expressions. There are a number of ways to do this.

  1. Use alternate delimiters. That's what I did here.
  2. Assign subexpressions to variables, and then expand them.
  3. Use lots of \ escapes.
  4. Put your subexpression in a file and read it.

Upvotes: 3

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed 's/$/ | sed -r '\''s\/abc\/xyz\/'\''/' file

Use '\'' to end the current single quote, then in the shell use \' to quote a single quote and finally a single quote to start the quoting of the sed command. Use \/ to quote the forward slash in the sed command.

As the substitution command can use any delimiter:

sed 's#$# | sed -r '\''s/abc/xyz/'\''#' file

reduces the amount of quoting and:

sed "s#$# | sed -r 's/abc/xyz/'#" file

reduces it further. However double quoting sed commands (or any utility) can have unwanted side effects i.e. metacharacters can be evaluated by the shell, so it is best to single quote and live with the "hole-like" mechanism '\''.

Upvotes: 0

anubhava
anubhava

Reputation: 786359

Use alternative delimiter in inner sed and double quote in outer sed to simplify your command:

sed "s/$/ | sed -r 's~abc~xyz~'/" file.ext

btw -r is not really needed in inner sed

Upvotes: 2

Related Questions