sed没有在shell脚本中使用for循环

时间:2015-10-19 14:54:45

标签: bash shell ubuntu sed

我试图替换' toReplace.txt'中的所有字符串。与' replaceList.txt'中指定的字符串匹配在bash 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

基本上我想用toReplace.txt中的所有浮点类型数替换replaceList.txt中此浮点类型数的索引(#行)。

Output for @narendra's code

@ narendra代码的输出如上所示。我的toReplace.txt仍然没有改变。任何人都知道问题是什么?

1 个答案:

答案 0 :(得分: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