Suhasini Subramaniam
Suhasini Subramaniam

Reputation: 161

how can I find and replace the string with quote?

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

Answers (3)

builder-7000
builder-7000

Reputation: 7657

Try:

NEWDIR=/mnt/
sed -i'' "s:^DIR=.*$:DIR='$NEWDIR':g" test.conf

Changes to the OP code:

  • Use : for sed's delimiter to avoid escaping slashes in NEWDIR
  • Use sed "..." instead of sed '...' to allow parameter expansion

test it with a here-string:

$ NEWDIR=/mnt/
$ sed "s:^DIR=.*$:DIR='$NEWDIR':g" <<< "DIR='/opt/'"
DIR='/mnt/'

Upvotes: 4

Melan Rashitha
Melan Rashitha

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

RavinderSingh13
RavinderSingh13

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

Related Questions