【问题标题】:sed not working in for loop in shell scriptsed 在 shell 脚本中的 for 循环中不起作用
【发布时间】:2016-01-17 23:44:30
【问题描述】:

我正在尝试使用 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

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

Output for @narendra's code

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

【问题讨论】:

  • 您能否提供文件中的示例?
  • 您正在尝试用数字替换 toReplace.txt 文件中来自 replaceList.txt 的字符串?
  • 尝试使用 while 循环而不是 cat 来归档变量,然后使用 FOR...while 循环读取行;做...你的代码在这里...完成
  • 我测试了您的代码以获得简单的示例,它按预期工作。图案中可以有空格吗?
  • @EtanReisner 是的,没错!

标签: bash shell ubuntu sed


【解决方案1】:

尝试如下...

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

【讨论】:

  • 你能解释一下它有什么不同吗?
  • 1.不建议使用for循环逐行读取文件...读取链接mywiki.wooledge.org/BashFAQ/001 2.如果行包含任何空格,它将被视为单行而不是将其分成多个项目
  • 感谢 narendra,我尝试了您的代码,但 toReplace.txt 中没有任何变化。输出如下:with 1 ....174533 with 2 ....349066 with 3 ....523599 with 4 ....698132 with 5 ....872665 with 6 ....0472 with 7 ....22173 with 8 ....39626 with 9 ....5708 with 10 ...74533 with 11 ...91986 with 12 ...09439 with 13 ...26893 with 14 ...44346 with 15 ...61799
  • 我只在输出中看到小数部分..看起来变量解释存在一些问题...您可以将变量放在大括号中...然后再试一次我更新了上面的答案...
  • 我尝试了您更新的代码,并上传了输出的屏幕截图。我的 toReplace.txt 中仍然没有任何变化...
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
  • 2013-04-29
  • 1970-01-01
  • 2022-01-27
  • 2022-05-17
相关资源
最近更新 更多