sed脚本中的Shell变量

sed脚本中的Shell变量,sed,Sed,sed命令在命令提示符下按预期工作,但在shell脚本中不工作 new_db_name=`echo "$new_db_name" | sed 's/$replace_string/$replace_with/'` 这是为什么?我如何修复它?对sed表达式使用双引号 new_db_name=$(echo "$new_db_name" | sed "s/$replace_string/$replace_with/") 如果您使用bash,这应该可以工作:

sed命令在命令提示符下按预期工作,但在shell脚本中不工作

new_db_name=`echo "$new_db_name" | sed 's/$replace_string/$replace_with/'`

这是为什么?我如何修复它?

sed
表达式使用双引号

new_db_name=$(echo "$new_db_name" | sed "s/$replace_string/$replace_with/")

如果您使用bash,这应该可以工作:

new_db_name=${new_db_name/$replace_string/$replace_with}

这对我使用env参数很有效

export a=foo
export b=bar

echo a/b | sed 's/a/'$b'/'

bar/b

根据变量的初始化方式,最好使用括号:

new_db_name=`echo "$new_db_name" | sed "s/${replace_string}`/${replace_with}/"
也许我遗漏了什么,但是
new\u db\u name=echo“$new\u db\u name”
在这里没有意义$new_db_name为空,因此您将返回一个空结果,然后返回sed命令的输出。要将stdout捕获为变量,不再建议使用反勾号。捕获被
$()
包围的输出

以以下为例:

replace_string="replace_me"
replace_with=$(cat replace_file.txt | grep "replacement_line:" | awk FS" '{print $1}')
其中replace_file.txt可能类似于:

old_string: something_old
I like cats
replacement_line: "shiny_new_db"

仅在sed表达式中使用变量
$replace\u with
是行不通的。bash没有足够的上下文来转义变量表达式
${replace_with}
告诉bash显式地使用变量发出的命令的内容。

伙计们:我使用以下命令使用sed将bash变量传递给bash脚本中的函数。也就是说,我将bash变量传递给sed命令

#!/bin/bash                            
function solveOffendingKey(){

    echo "We will delete the offending key in file: $2, in line: $1"
    sleep 5
    eval "sed -i '$1d' $2"
}


line='4'
file=~/ivan/known_hosts
solveOffendingKey $number $file

亲切的问候

使用单引号时,变量不会被替换为它们的值。如果要替换所有变量(请注意双引号)
new\u db\u name=${new\u db\u name//$replace\u string/$replace\u With}
#!/bin/bash                            
function solveOffendingKey(){

    echo "We will delete the offending key in file: $2, in line: $1"
    sleep 5
    eval "sed -i '$1d' $2"
}


line='4'
file=~/ivan/known_hosts
solveOffendingKey $number $file