'Replace string in a file with url present in another file in shell script
I was like trying to replace a string in a file with the url present in another file using sed command. for example... let url.txt be the file that contains url:
https://stackoverflow.com/questions/1483721/shell-script-printing-contents-of-variable-containing-output-of-a-command-remove
and demo.txt contains
Replace_Url
the sed command I used is:
sed -i "s/Replace_Url/$(sed 's:/:\\/:g' url.txt)/" demo.txt
there comes no error but the string hasn't been replaced..
Solution 1:[1]
It'd be hard to do this job robustly with sed since sed doesn't support literal string operations (see Is it possible to escape regex metacharacters reliably with sed), so just use awk instead, e.g.:
awk -v old='Replace_Url' '
NR==FNR { new=$0; next }
s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+length(old)) }
{ print }
' url.txt demo.txt
Solution 2:[2]
sed -i "s@Replace_Url@$(<url.txt)@" demo.txt
it works
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ed Morton |
| Solution 2 |
