我需要根据传递给我的bash脚本程序的国家/地区输入替换特定的字符串
我正在尝试更改现有代码
table_value=$1
ctry_input=$2
final_var=$(echo ${table_value}| sed -e "s/\@ctry/${ctry_input}/")
输入值
if table_value=random_@ctry_final
and ctry=KL
then final_var=random_KL_final
if table_value=source_@ctry_final
and ctry in (nz,uk,us)
then final_var=source_nz_final subsequently the string would be replaced for uk and us
if table_value=source_@ctry_final
and ctry in (aus,cn)
then final_var=diff_aus_final. In this case source_@ctry_final should be replaced as diff_aus_final. source string needs to be replaced as diff for countries under aus,cn
是否可以调整现有的变量代码,而不是使用if
答案 0 :(得分:1)
我在echo "${table_value}"
中添加了引号,该引号对于解决方案不是必需的,但这是一个好习惯。
我使用sed
选项-r
来避免特殊字符的反斜杠(不需要选项-e
)。
在原始代码之后,我添加了一条附加命令,当字符串看起来像source_aus_
或source_cn_
时替换了一部分。
final_var=$(echo "${table_value}"| sed -r "s/\@ctry/${ctry_input}/;s/source_(aus|cn)_/diff_\1_/" )