awk脚本在双引号内替换第二次出现的字符串

时间:2012-10-28 15:47:56

标签: awk replace double-quotes

我在编写脚本以替换双引号内的字符串时遇到问题。文件部分如下所示:

"regA~1"    :   "FF_NODE~94"
"regA~2"    :   "FF_NODE~105"
"regA~3"    :   "FF_NODE~116"
"regA~4"    :   "FF_NODE~127"
"regA~5"    :   "FF_NODE~138"
"regA~6"    :   "FF_NODE~149"
"regA~7"    :   "FF_NODE~154"
"regA~8"    :   "FF_NODE~155"
"regA~9"    :   "FF_NODE~156"
"regA~1"    :   "FF_NODE~95"
"regA~11"   :   "FF_NODE~96"

如果我这样做就行了

awk '/"regA~1"/{c++;if(c==2){sub("regA~1","regA~10");}}1' file > file_out

但是当我尝试将这个脚本传递给我时,我传递一个变量regA~1而c的值不起作用。

s="regA~1";
r="regA~10";
n=2;

awk -v search="$s" -v replace="$r" -v count=$n '/search/{c++;if(c==count){sub(search,replace);}}1' file > file_out

我也试过

awk -v search=$s -v replace=$r -v count=$n '/search/{c++;if(c==count){sub(search,replace);}}1' file > file_out

2 个答案:

答案 0 :(得分:1)

匹配在变量中存储为字符串的RE所需的语法是

$0 ~ var

/var/

答案 1 :(得分:0)

感谢Ed Morton提示。这是bash脚本,以防任何人需要这样的东西。不是很复杂,但它对我有用。

#!/bin/bash
# Replaces a specific occurrence of a search string with a replace string
if [ $# -lt 4 ] ; then
echo -e "Wrong number of parameters."
echo -e "Usage:"
echo -e "repnthstr file search replace n"
echo -e "repnthstr fileext search replace n"
exit 1
fi

for file in $1
 do
 if [ -f $file -a -r $file ]; then
   awk -v search=$2 -v replace=$3 -v cnt=$4 '$0 ~ search{c++;if(c==cnt){sub(search,replace);}}1' "$file" > temp && mv temp "$file"
 else
  echo "Error: Cannot read $file"
 fi
done
相关问题