Sed for replacing text using bash shell variables

While using the command “sed” for find and replace, I wanted to know how one could find a constant and replace it with a variable inside the quotation syntax of sed?

I wanted to replace constant 3 with variable name “hourid”
Here is what I tried.

sed -i 's@3@hourid$@g' file_name.txt

I want to know how to provide a right syntax for replacing variable “hourid”

Your suggestions are greatly appreciated

Welcome @achandra81 to nixCraft forum.

You need to put syntax is double quote for shell expansion for variables. For example:

sed -i "s/find/replace/g" file

Say you need to find 3 and replace with the contents of variable named $foo:

foo="xyz"
sed -i "s/3/$foo/g" file

To replace constant 3 with variable name “hourid”:

sed -i "s/3/\$hourid/g" file

OR

sed -i 's@3@\$hourid@g' file_name.txt

OR

sed -i 's@3@$hourid@g' file_name.txt

HTH

1 Like

Thank you Vivek for your quick response.
This site is very informative. I try to engage and help others.

Arun

1 Like