Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a string in file using shell script

Tags:

bash

shell

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' 
like image 541
Pritom Avatar asked Dec 13 '11 09:12

Pritom


People also ask

How do you replace a string in a file in shell script?

Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do I replace text in a file?

To replace found text: Select the Replace tab, and then select the Replace with box. Select Special, select a wildcard character, and then type any additional text in the Replace with box. Select Replace All, Replace, or Find Next.


1 Answers

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
like image 200
luketorjussen Avatar answered Oct 01 '22 20:10

luketorjussen