【问题标题】:Bash ,Find and Replace a string with a parameterized value generated inside the code?Bash,用代码中生成的参数化值查找和替换字符串?
【发布时间】:2020-04-14 11:09:28
【问题描述】:

以下链接我已经尝试过但失败了:

find and replace string in a file

这似乎很容易解决,但我被卡住了,无法解决

所以我有一个文件,里面有多个字段,如下所示:

env : $env

user : abc

passowrd : xyv

tablename : cat_$env 

tablelocation : hdfs://home/ak/cat_$env

所以我的要求是将$env 替换为$env_details(我在我的shell 脚本中生成) 表示$env_details 的值在每次运行时都会不断变化,我尝试了以下命令但出现错误:

sed -i "s/$env/$env_details/g" "$filename"

Error: sed: -e expression #1 , char 0 no previous regular expression

你能帮我解决我的错误吗?

【问题讨论】:

标签: bash shell unix


【解决方案1】:

您的错误是,如果 $env 在双引号内,shell 会尝试扩展它,就像它扩展 $filename 一样。简单写

sed -i 's/$env/$env_details/g' "$filename"

如果要替换为$env_details 内容,保留双引号并将$env$ 转义:

sed -i "s/\$env/$env_details/g" "$filename"

【讨论】:

    猜你喜欢
    • 2012-06-06
    • 2012-06-26
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多