• Uncategorized

About bash : Insert-single-quote-with-sed

Question Detail

I want to add some text on a line:

sudo sed -i '5imytext 16/16' /file

Now I’ve added mytext 16/16 on line 5 of the file, but I actually want to add the text 'mytext' 16/16 (mytext between single quotes).

I tried

sudo sed -i '5i'mytext' 16/16' /file

but it didn’t work. Can someone help me?

Question Answer

The single quotes that you’re trying to use in your insertion string are interfering with the ones around the sed command.

The simplest thing to do is to use different quotes around your sed command:

"5i'mytext' 16/16"

Normally it’s best to use single quotes around a sed command but it would be more tricky in this case:

'5i'"'"'mytext'"'"' 16/16'

Basically, you need to put the single quotes inside double quotes somehow and in this case there’s no reason not to double quote the whole command.

As suggested by 123 in the comments, an alternative would be to put your sed command into a script file:

5i'mytext' 16/16

Then use the -f switch to sed:

sed -f script

This avoids the need to use two kinds of quotes.

Use double quote in these cases. Because:

  1. Single quote can’t have single quote inside it. ('\'' won’t work)
  2. Double quote can have both single quote and double quote inside it. ("'\"" will work)

Example:

sudo sed -i "5i'mytext' 16/16" /file

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.