Reputation: 43
I Want to search variable and replace with its absolute path in file.
setenv ABC /home/xyz
cat file.txt
${ABC}/Test/Folder_1
${ABC}/Test/Folder_2
I want to replace all occurance of the ${ABC} by /home/xyz. I tried by the below mentioned way, but does not work,
sed -i 's/\$ABC/echo $ABC/g' file.txt
I can do by below mentioned way, but I do not want to do this way.(I have to put so many back slash)
$ echo $ABC | sed -i 's/\$ABC/\/home\/xyz/g' file.txt
Please give me some suggestion for this question.
Thank You.
Upvotes: 0
Views: 1339
Reputation: 3225
Another way to get the absolute path is readlink -f ${ABC}/Test/Folder_2
Or the perl alternative to your slash hungry command
$ echo $ABC | sed -i 's/\$ABC/\/home\/xyz/g' file.txt
would be
$ echo $ABC | perl -p -i -e 's!\$ABC!/home/xyz!g'
the first character after the 's
above will be used as the delimiter in the replacement expression (i.e. 's@foo@bar@g'
)
Upvotes: 0
Reputation: 1306
Character after s
in sed
is the delimiter and it can be any one character of your choice and it works as long as it's not in the string-to-be-matched
and string-to-be-replaced
.
Example :
sed 's:string-to-be-matched:string-to-be-replaced:g' file-to-be-edited
:
is the delimiter
g
means global replacement.
In your case, as the string-to-be-replaced
contains the /
, the same you are using as sed delimiter.
Simple Solution will be :
sed -i 's:${ABC}:'"$ABC"':g' fill.txt
'"
is at either end of $ABC in the replacement string. Purpose is to expand shell variable to use with sed
Upvotes: 1
Reputation: 9321
If you really want to use the value from a variable in your replacement string, you could use
sed "s#\${ABC}#$ABC#g" file.txt
Upvotes: 1