我正在尝试使用变量输入和替换字符串迭代搜索和替换文件中的字符串。我曾尝试使用 sed 和 awk 并且似乎确定它实际上是给我带来问题的关联数组值(?)。
我正在查看这样的关联数组:
declare -A speedReplaceValuePairsText
speedReplaceValuePairsText["20"]="xthirtyx"
speedReplaceValuePairsText["30"]="xfiftyx"
speedReplaceValuePairsText["40"]="xsixtyx"
speedReplaceValuePairsText["50"]="xeightyx"
speedReplaceValuePairsText["60"]="xhundredx"
为方便起见,我首先声明了我的替换变量:
for speedBeforeValue in "${!speedReplaceValuePairsText[@]}";
do
findValue=${speedBeforeValue}
replaceWithValue=${speedReplaceValuePairsText[$speedBeforeValue]}
#replaceWithValue="blah"
echo " Replacing $findValue with $replaceWithValue..."
awk -v srch="$findValue" -v repl="$replaceWithValue" '{gsub(srch,repl); print}' infile.txt > outfile.txt
#sed 's/'"$findValue"'/'"$replaceWithValue"'/g' infile.txt > outfile.txt
#sed "s/$findValue/$replaceWithValue/g" $scriptDir/$currentFileName > outfile.txt
done
注释掉的行是我尝试过的类似中间版本的替代版本。
我试过只使用普通字符串(注释掉的“blah”),效果很好。
最奇怪的部分是 echo 语句为键和值显示了正确的值。
我尝试了很多组合,我都快疯了。请有人告诉我我在这里做一些愚蠢的事情。
注意:这是嵌套在另一个循环中,但我不认为这是一个问题,如果我错了,请告诉我
编辑:我已经简化了输入和输出文件,并澄清一下,如果我尝试使用我的关联数组值,则不会替换任何内容。但是如果我使用像“blah”这样的虚拟字符串,它就可以工作。
奖励:我在下面标记了答案,但我的搜索和替换值以双引号开始和结束,但无论我尝试什么,它都会替换 60 的所有实例。我怎样才能让它用“xsixtyx”替换“60”?
谢谢
我认为您想在循环中使用>>
而不是使用>
?
awk -v srch="$findValue" -v repl="$replaceWithValue" '{gsub(srch,repl); print}' $scriptDir/$currentFileName >> ./$outputFolderName/$currentFileName
我试图运行你的代码,它按预期工作,除了>
.
或者,如果您只想查看替换的结果
awk -v srch="$findValue" -v repl="$replaceWithValue" '{ if (gsub(srch,repl)) print}' $scriptDir/$currentFileName >> ./$outputFolderName/$currentFileName
对于一个文件
30
20
60
输出看起来像
xthirtyx
xhundredx
xfiftyx
对于第二种情况。
这是我尝试过的完整 bash 脚本
#!/bin/bash
declare -A speedReplaceValuePairsText
speedReplaceValuePairsText["20"]="xthirtyx"
speedReplaceValuePairsText["30"]="xfiftyx"
speedReplaceValuePairsText["40"]="xsixtyx"
speedReplaceValuePairsText["50"]="xeightyx"
speedReplaceValuePairsText["60"]="xhundredx"
for speedBeforeValue in "${!speedReplaceValuePairsText[@]}";
do
findValue=${speedBeforeValue}
replaceWithValue=${speedReplaceValuePairsText[$speedBeforeValue]}
echo " Replacing $findValue with $replaceWithValue..."
awk -v srch="$findValue" -v repl="$replaceWithValue" '{if (gsub(srch,repl)) print}' test.txt >> /tmp/test.txt
done
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句