2012-10-28 68 views
2

我無法制作腳本來替換雙引號內的字符串。該文件的部分看起來是這樣的:awk腳本替換雙引號內的字符串第二次出現

"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 

而是力圖使這個腳本,我傳遞一個變量雷加〜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 

回答

1

你需要匹配一個儲存在一個變量字符串的RE的語法是

$0 ~ var 

/var/ 
+0

我換成/搜索/以$ 0〜搜索和現在的工作。謝謝。 – geo

0

謝謝埃德莫頓的小費。如果有人需要這樣的東西,這裏是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 
+0

請注意,您的腳本正在用給定字符串替換與字符串匹配的字符串,而不是用字符串替換給定字符串。如果你真的只想搜索一個字符串,你需要使用index(),length()和substr()而不是〜和sub()。如果「搜索」恰巧包含任何RE元字符(如+,*等),則會看到差異 –