Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux SED command in Bash script strips ' from string

Tags:

linux

sed

strip

I have been putting together a bash script and within it I need to update a file with some neccasary information. The command I am using is below:

sudo sed '
/end/ a\
First line to update\
  param 1 'var1'\
  param 2 'var2'\
  param 3 'var3'\
  param 4 'var4'\
end\
' TestFile >TestFileNew

Now this should update the file with the data and should look like this:

end
First line to update
  param 1 'var1'
  param 2 'var2'
  param 3 'var3'
  param 4 'var4'
end

The file does get created and the data is in it however it seems to strip the ' symbols from the text and I don't want this to happen, can anyone please help?? An example of what is actually getting produced is below:

end
First line to update
  param 1 var1
  param 2 var2
  param 3 var3
  param 4 var4
end
like image 832
user723858 Avatar asked Dec 15 '22 21:12

user723858


2 Answers

Use "" as the outer quotes:

sudo sed "
/end/ a\\
First line to update\\
  param 1 'var1'\\
  param 2 'var2'\\
  param 3 'var3'\\
  param 4 'var4'\\
end\\
" TestFile >TestFileNew
like image 69
Igor Chubin Avatar answered Jan 05 '23 17:01

Igor Chubin


Looks like Igor has already provided an answer that may work for the single quotes.

Regarding the file creation, remember that sudo affects the program (sed) you're running as its option. It does not affect redirection, which is handled by your shell. So if you don't have permission as a user to write TestFileNew, sudo won't help you, the way you're using it above.

You might be better off creating your output somewhere else, then using sudo to move it into place.

sudo sed "/end/ ..." TestFile > /tmp/TestFileNew
sudo mv /tmp/TestFileNew ./TestFileNew

Alternately, this whole script could be run with sudo... I.e. /path/to/myscript is:

#!/bin/bash

sed "/end/ ..." TestFile > TestFileNew

then:

$ sudo /path/to/myscript

Then sudo is running bash instead of sed, and the privileged bash instance is responsible for handling redirection within the script.

like image 22
ghoti Avatar answered Jan 05 '23 17:01

ghoti