我想知道如何实现在我的bash脚本中查找和替换字符串的函数,例如:
#!/bin/bash
if [ $1 -eq 1 ] then
ListToReplace="'Static_value as Column1','Static_value2' as Column2"
Searching which query contain Column1, Column2 , then Somehow replace in queries...
else
do nothing.
fi
query="Select Column1, Column2 from dual"
run query
query2="Select Column3, Column1 from dual"
run query2
让我们假设我们将使用变量1运行脚本,然后query
应该看起来:
Select 'Static_value' as Column1,'Static_value2' as Column2 from dual
和query2
:
Select Column3, Static_value as Column1 from dual
变量0然后:
Select Column1,Column2 from dual
Select Column3,Column1 from dual
任何提示?感谢
答案 0 :(得分:1)
bash
中的替换非常简单,但我不确定您为什么需要/想要列表:
#!/bin/bash
query="Select Column1, Column2 from dual"
query2="Select Column3, Column1 from dual"
if [ "${1:-0}" -eq 1 ]; then
for VAR in query query2; do
VAL=${!VAR}
VAL=${VAL/Column1/Static_value as Column1}
VAL=${VAL/Column2/\'Static_value2\' as Column2}
eval $VAR=\$VAL
done
fi
echo run $query
echo run $query2
VAL=${!VAR}
按名称读取变量的值。 eval $VAR=\$VAL
按名称指定变量的值。 (请参阅here for more。)${//}
扩展会在值内执行替换。