Replace the line in the file with a shell script

Suppose my a.conf file is as follows

Include /1 Include /2 Include /3 

I want to replace "Include / 2" with a new line, I am writing code in a .sh file:

 line="Include /2" rep="" sed -e "s/${line}/${rep}/g" /root/new_scripts/a.conf 

But after running the sh file, it gives me the following error

 sed: -e expression #1, char 14: unknown option to `s' 
+4
source share
3 answers

If you are using a newer version of sed, you can use -i to read and write to the same file. Using -i , you can specify the file extension so that a backup is made if something goes wrong. Also you do not need to use the -e flag unless you use multiple commands

 sed -i.bak "s/${line}/${rep}/g" /root/new_scripts/a.conf 

I just noticed that since the variables you use are quotes, you can use single quotes around your sed expression. In addition, your line contains a slash to avoid errors, you can use a different delimiter in the sed command (the delimiter should not be a slash):

 sed -i.bak 's|${line}|${rep}|g' /root/new_scripts/a.conf 
+14
source

You need to write the changes to the new file, and then move the new file over the old one. Like this:

 line="Include 2" rep="" sed -e "s/${line}/${rep}/g" /root/new_scripts/a.conf > /root/new_scripts/a.conf-new mv /root/new_scripts/a.conf-new /root/new_scripts/a.conf 
+3
source

Redirection ( > /root/new_scripts/a.conf ) erases the contents of the file before sed can see it.

You need to pass the -i option to sed in order to edit the file in place:

 sed -i "s/${line}/${rep}/g" /root/new_scripts/a.conf 

You can also ask sed to back up the source file:

 sed -i.bak "s/${line}/${rep}/g" /root/new_scripts/a.conf 
+3
source

Source: https://habr.com/ru/post/1386063/


All Articles