Three ways to use variables in sed command
Contents of file name.txt:
name=rose
Change the rose in the name.txt file to tomas through update.sh
method one:
Content in update.sh file:
#!/bin/bash
name=tomas
sed -i 's/rose/'"${name}"'/g' b.txt
Description: Use single quotes for the sed command, and use single quotes + double quotes for variables to include variables
Method two:
#!/bin/bash
name=tomas
sed -i "s/rose/${name}/g" name.txt
Note: The sed command uses double quotes, and the variable can be directly quoted
Method three:
#!/bin/bash
name=tomas
eval sed -i 's/rose/${name}/g' name.txt
Description: The sed command uses single quotes and the variables are directly quoted, but the sed command needs to be executed through eval, and eval will scan the following shell commands twice. If the shell command is a normal command after the first scan, execute this command ; if the shell command contains an indirect reference to a variable, the semantics of the indirect reference are guaranteed.