簡體   English   中英

sed在shell腳本中無法在for循環中工作

[英]sed not working in for loop in shell script

我正在嘗試使用bash shell腳本中的for循環用整數索引逐一替換'toReplace.txt'中與'replaceList.txt'中指定的字符串匹配的所有字符串:

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

基本上,我想將toReplace.txt中的所有浮點類型編號替換為replaceList.txt中該浮點類型編號的索引(行號)。

@narendra代碼的輸出

@narendra代碼的輸出如上。 我的toReplace.txt仍然沒有任何變化。 任何人都知道問題是什么嗎?

嘗試如下...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM