Reputation: 161
how can I find replace the string with the quote ?
Input file:-
cat test.conf
DIR='/mnt/'
I would like to replace the variable NEWDIR, the variable could be "/opt" or "/mnt/iso"
Note:- also single quote in the input file should be maintained.
NEWDIR="/opt/"
sed -i 's/^DIR=.*$/DIR=$NEWDIR/' test.conf
but it doesn't seem to be replacing the string
cat test.conf
DIR='/mnt/'
Upvotes: 2
Views: 76
Reputation: 7657
Try:
NEWDIR=/mnt/
sed -i'' "s:^DIR=.*$:DIR='$NEWDIR':g" test.conf
Changes to the OP code:
:
for sed's delimiter to avoid escaping slashes in NEWDIR
sed "..."
instead of sed '...'
to allow parameter expansiontest it with a here-string:
$ NEWDIR=/mnt/
$ sed "s:^DIR=.*$:DIR='$NEWDIR':g" <<< "DIR='/opt/'"
DIR='/mnt/'
Upvotes: 4
Reputation: 504
Use double quotes instead of single quotes your looks will be like this
sed -i "s/^DIR=.*$/DIR=$NEWDIR/" test.conf
Upvotes: 1
Reputation: 133770
Could you please try following.
var="/opt" ##A shell variable.
awk -v s1="\"" -v value="$var" '{gsub(/\047\/mnt\/\047/,s1 value s1)} 1' Input_file
In case you want to save output into Input_file itself use:
awk -v s1="\"" -v value="$var" '{gsub(/\047\/mnt\/\047/,s1 value s1)} 1' Input_file > temp && mv temp Input_file
Upvotes: 2