2015-10-19 79 views
0

我試圖用'bash shell'中的for循環來替換與'replaceList.txt'中指定的字符串匹配的'toReplace.txt'中的所有字符串。腳本:sed在shell腳本中不工作for循環

source='toReplace.txt' 
map='replaceList.txt' 
label=`cat $map` 
index=1 
for item in $label 
do 
    sed -i "s/$item/$index/g" $source 
    index=$((index + 1)) 
done 

但是sed命令效果很好圈外或在命令行控制檯,但一旦我把它放在for循環它不工作了。如果我運行上面的代碼,那麼toReplace.txt實際上沒有任何變化。

任何人有任何想法這裏有什麼問題嗎?非常感謝!

謝謝大家的見解!的.txt文件

#toReplace.txt 
3.66519 0 
5.75959 0 
1.39626 1.0472 
5.23599 0.174533 
1.91986 0.698132 
1.0472 1.0472 
2.61799 0.698132 

#replaceList 
0.174533 
0.349066 
0.523599 
0.698132 
0.872665 
1.0472 
1.22173 
1.39626 
1.5708 
1.74533 
1.91986 
2.09439 
2.26893 
2.44346 
2.61799 

的示例基本上我想在此replaceList.txt浮子式編號的索引(線的#)來代替在toReplace.txt所有浮子式數字。

Output for @narendra's code

輸出爲@納倫德拉的代碼是如上。我的toReplace.txt中仍然沒有任何變化。任何人都知道這個問題是什麼?

+1

你能提供的是什麼文件,請例子嗎? – 123

+0

您試圖用數字替換'toReplace.txt'文件中'replaceList.txt'的字符串嗎? –

+0

嘗試使用while循環代替cat來變量中的文件,然後使用FOR ... while read line循環;做...你的代碼在這裏...完成<$ map – narendra

回答

0

嘗試如下...

source='toReplace.txt' 
map='replaceList.txt' 
index=1 
while read item 
do 
    # comment below echo once done testing 
    echo "replacing $item with $index ..." 
    sed -i "s/${item}/${index}/g" $source 
    index=$((index + 1)) 
done < $map 
+0

你能解釋一下它有什麼不同嗎? –

+1

1.不建議使用for循環逐行讀取文件...閱讀鏈接http://mywiki.wooledge.org/BashFAQ/001 2.如果行包含任何空格,它將被視爲單行而不是將其分成多個項目 – narendra

+0

謝謝narendra,我試過你的代碼,但沒有改變toReplace.txt。的輸出是這樣的:與'1 .... 174533 與2 .... 349066 與3 .... 523599 與4 .... 698132 與5 .... 872665 6 .. ..0472 與7 .... 22173 與8 .... 39626 與9 .... 5708 與10 ... 74533 11 ... 91986 12 ... 09439 與13 ... 26893 with 14 ... 44346 with 15 ... 61799' – DrinkingSprout