-1

Good day everyone, I followed the following Find and Replace Inside a Text File from a Bash Command.

Now I am using the sed solution which seems to work if I use two predifined strings, but I want to replace the contents with something that is in a file, and not defined by me.

I have a file with the words "kung fu dog" i want it to be replace the word "dog" with the word "panda" but that word is in another file. I tried doing:

sed -i 's/dog/$(cat filethatcontainspanda)/g' /home/myhome

but the problem is that instead of having the word dog replaced with panda, I got the word "dog" replaced with "$(cat filethatcontainspanda)" so in the end instead of having "kung fu panda", I have "kung fu $(cat filethatcontainspanda)". Is there any workaround to this?

Community
  • 1
  • 1
  • 3
    Did you try double quotes: `sed -i "s/dog/$(cat filethatcontainspanda)/g" /home/myhome` – anubhava Jun 23 '14 at 14:25
  • 1
    Yup that solved it the double quotes worked fine, i tried double quotes around the first time like so sed -i 's/dog/"$(cat filethatcontainspanda)"/g' /home/myhome it didn't work, but your solution works great thanks a lot. – user234688 Jun 23 '14 at 14:35
  • @user234688 Double quotes inside single quotes have no special meaning - you're still inside a string that is protected from expansion. – Felix Frank Jun 23 '14 at 14:37
  • could also leave it out of quotes altogether `'s/dog/'$(cat filethatcontainspanda)'/g'` –  Jun 23 '14 at 14:45
  • possible duplicate of [variable in sed](http://stackoverflow.com/questions/9506537/variable-in-sed) – tripleee Jun 23 '14 at 14:55
  • @jidder: NO, having quotes is much better, unless you really trust the input. – anishsane Jun 23 '14 at 15:32
  • @anishsane `'s/dog/'"$(cat filethatcontainspanda)"'/g'` That would be okay though wouldnt it ? I just meant that all of it doesnt need to be in the same quotes. If there were no spaces quotes are not needed at all. –  Jun 24 '14 at 07:04
  • Could also use `$( –  Jun 24 '14 at 07:43

2 Answers2

0

You need to use double quotes " instead of single ' and awk instead of cat:

sed -i "s/dog/$(awk '{print $1}' filethatcontainspanda)/g" /home/myhome
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
0

You must use " instead '

sed -i "s/dog/$(cat filethatcontainspanda)/g" /home/myhome
Madvin
  • 770
  • 9
  • 15