Pritom
Pritom

Reputation: 1333

replace a string in file using shell script

Suppose my file a.conf is as following

Include /1
Include /2
Include /3

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

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

But after running the sh file, It give me the following error

sed: -e expression #1, char 14: unknown option to `s' 

Upvotes: 8

Views: 53217

Answers (4)

Akarsh Srivastava
Akarsh Srivastava

Reputation: 141

So, if you have to replace a substring in a file, you can use sed command like this, say we have a file as file.txt, so replacing a substring in it can be done like this

searchString="abc";
replaceString="def";
sed -i '' "s|$searchString|$replaceString|g" file.txt

This will all the occurrences of "abc" with "def" in file.txt. Also, this keeps a check for any / character present in the variables used, and with no backup file made.

Upvotes: 1

luketorjussen
luketorjussen

Reputation: 3264

If you are using a newer version of sed you can use -i to read from and write to the same file. Using -i you can specify a file extension so a backup will be made, incase something went wrong. Also you don't need to use the -e flag unless you are using multiple commands

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

I have just noticed that as the variables you are using are quoted strings you may want to use single quotes around your sed expression. Also your string contains a forward slash, to avoid any errors you can use a different delimiter in your sed command (the delimiter doesn't need to be a slash):

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

Upvotes: 21

Eugene Yarmash
Eugene Yarmash

Reputation: 150178

The redirection (> /root/new_scripts/a.conf) wipes the contents of the file before sed can see it.

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

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

You can also ask sed to create a backup of the original file:

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

Upvotes: 4

Ivan Dimitrov
Ivan Dimitrov

Reputation: 41

You have to write the changes to a 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

Upvotes: 4

Related Questions