-1

Hello there I have run into that problem:

The following code does not replace line that contains $variable1 with the content of $variable2:

variable1=$(cat pathtofile1 | grep -w "something.more")
variable2=$(cat pathtofile2 | grep -w "something.else")

sed -i 's/$variable1/$variable2/g' pathtofile1

I want to copy the entire line from one file to another but it doesn't work, I think it has to do something with the dots in the variable's content but I don't seem to get it fixed no matter what.

Can someone help?

Thanks in advance.

EDIT: Edited the question because it was not clear enough what I wanted to do. I want to replace the line in file1 that contains the quoted text with the line of file2 that contains the second quoted text.

3rr0r 404
  • 1
  • 2

1 Answers1

1

First you need to use doublequotes instead of simple quotes for your variables to be interpreted as such. Then you need to escape the dots in your variables to be interpreted as dot characters and not regex interpretation that says any character.

Also you're not setting you variables right.

yoones@laptop:/tmp/toto$ cat f1
toto #aabbcc
titi #fff000
tata #212322
yoones@laptop:/tmp/toto$ cat f2
hello #ababab
good #123456
morning #fafafa
yoones@laptop:/tmp/toto$ cat x.sh 
#!/bin/bash

variable1=$(cat f1 | fgrep '#fff00' | sed -e 's/[]\/$*.^|[]/\\&/g')
variable2=$(cat f2 | fgrep '#fafafa' | sed -e 's/[]\/$*.^|[]/\\&/g')

sed -i "s/$variable1/$variable2/g" f1
yoones@laptop:/tmp/toto$ ./x.sh 
yoones@laptop:/tmp/toto$ cat f1
toto #aabbcc
morning #fafafa
tata #212322
yoones@laptop:/tmp/toto$ cat f2
hello #ababab
good #123456
morning #fafafa
yoones@laptop:/tmp/toto$ 
yoones
  • 2,394
  • 1
  • 16
  • 20