-1

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..

1
  • sed -i "s@Replace_Url@$(<url.txt)@" demo.txt Commented Mar 16, 2022 at 16:43

2 Answers 2

0

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
Sign up to request clarification or add additional context in comments.

Comments

0

sed -i "s@Replace_Url@$(<url.txt)@" demo.txt it works

2 Comments

That would fail given various contents of url.txt, e.g. & or \1 or @.
Please read "How to Answer" and "Explaining entirely code-based answers". It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.