Reputation: 145
I have searched this topic and saw some examples but somehow it doesnt work for me. i have to replace one line with another in a file in shell script (which contains file path and extension). I am using below command but replace is not working.
line='a|b|c|\\folder\file.txt'
upd_line='a|b|c|\\folder\file.txt|d'
sed -i 's#$line#$upd_line#g' sample.txt
sample.txt content:
HDR|date
a|b|c|\\folder\file.txt
I am expecting second line to be replaced with content of $upd_line but it remains unchanged. Please advise what am i doing wrong. i tried in bash and ksh with no luck.
Upvotes: 1
Views: 450
Reputation: 23677
perl
would be better suited with quote operators
$ cat sample.txt
HDR|date
a|b|c|\\folder\file.txt
$ # adding |d to end of line
$ line='a|b|c|\\folder\file.txt'
$ perl -pe "s/$/|d/ if /\Q$line/" sample.txt
HDR|date
a|b|c|\\folder\file.txt|d
$ # generic search and replace
$ l='a|b|c|\\folder\file.txt' ul='a|b|c|\\folder\file.txt|d' perl -pe 's/\Q$ENV{l}/$ENV{ul}/' sample.txt
HDR|date
a|b|c|\\folder\file.txt|d
perl -i -pe
for inplace editing-i
and -pe
optionsUpvotes: 1
Reputation: 58473
This might work for you (GNU sed & bash):
a='a|b|c|\\folder\file.txt'
b='a|b|c|\folder\file.txt|d'
qs(){ sed <<<$1 's/[][\\.*^$]/\\&/g';}
sed "s/$(qs $a)/$(qs $b)/" file
This creates a function qs
which converts the variable strings to the accepted form in the sed regexp and replacement.
N.B. the use of double quotes around the sed command; this allows the shell to interpolate the shell variables and function calls. If GNU readline is used in your choice of terminal, C-M-e will show you the results of the interpolation before the shell runs the sed command (you may need to requote the results before running them for real).
Upvotes: 2
Reputation: 5298
It will be something like this:
line="a|b|c|\\\\\\\folder\\\file.txt"
sed -i "s#$line#&|d#g" sample.txt
Output:
HDR|date
a|b|c|\\folder\file.txt|d
Upvotes: 2