Linux SED command in Bash script strips' from string

I have compiled a bash script, and in it I need to update the file with some additional information. The command I'm 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 data file 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 is created and the data in it, however, it seems to strip characters from the text, and I do not want this to happen, can anyone help? An example of what is actually being produced is shown below:

 end First line to update param 1 var1 param 2 var2 param 3 var3 param 4 var4 end 
+4
source share
4 answers

Use "" as external quotation marks:

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

It seems that Igor has already provided an answer that might work for single quotes.

As for creating the file, remember that sudo affects the program ( sed ) that you run as its option. This does not affect the redirection that your shell handles. Therefore, if you do not have permission to write TestFileNew user, sudo will not help you, as you use it above.

You might be better off creating an exit elsewhere, and then use sudo to move it to a place.

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

Alternatively, this entire script can be run using sudo ... Ie /path/to/myscript :

 #!/bin/bash sed "/end/ ..." TestFile > TestFileNew 

then

 $ sudo /path/to/myscript 

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

+4
source

Sometimes you have to deal with two types of quotes (for example, html and javascript). Then it’s very convenient to put sed commands in a script:

 cat >FILE end cat >script.sed /end/ a\ First line to update\ param 1 'var1'\ param 2 'var2'\ param 3 'var3'\ param 4 'var4'\ end sed -f script.sed FILE end First line to update param 1 'var1' param 2 'var2' param 3 'var3' param 4 'var4' end 
+1
source

In this case, it would probably be easier to use the sed r command:

 $ cat > /tmp/repl << EOF First line to update param 1 'var1' param 2 'var2' param 3 'var3' param 4 'var4' end EOF $ sed '/end/r/tmp/repl' TestFile $ rm /tmp/repl 

(I ignored the sudo / redirect problem, but you probably want sudo sh -c 'sed /end/r/tmp/repl/ TestFile > TestFileNew'

+1
source

All Articles