Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert single quote with sed

Tags:

bash

shell

sed

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?

like image 241
lvthillo Avatar asked Jan 28 '16 13:01

lvthillo


2 Answers

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.

like image 167
Tom Fenech Avatar answered Oct 04 '22 20:10

Tom Fenech


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
like image 44
Jahid Avatar answered Oct 04 '22 20:10

Jahid