Replace a string in shell script using a variable

Viewed 541069

I am using the below code for replacing a string inside a shell script.

echo $LINE | sed -e 's/12345678/"$replace"/g'

but it's getting replaced with $replace instead of the value of that variable.

Could anybody tell what went wrong?

11 Answers

Let me give you two examples.

  • Using sed:
#!/bin/bash
LINE="12345678HI"
replace="Hello"
echo $LINE | sed -e "s/12345678/$replace/g"
  • Without Using sed:
LINE="12345678HI"
str_to_replace="12345678"
replace_str="Hello"
result=${str//$str_to_replace/$replace_str}
echo $result

Hope you will find it helpful!

I had a similar requirement to this but my replace var contained an ampersand. Escaping the ampersand like this solved my problem:

replace="salt & pepper"
echo "pass the salt" | sed "s/salt/${replace/&/\&}/g"

Use this instead

echo $LINE | sed -e 's/12345678/$replace/g'

this works for me just simply remove the quotes

Related