【问题标题】:Errors Integrating SED into a Bash Loop将 SED 集成到 Bash 循环中的错误
【发布时间】:2014-10-09 15:03:29
【问题描述】:

我编写的 bash 脚本有问题。该命令在 SED 之前一直有效,我不确定我做错了什么。 HAL 是我要替换的文本文件中的变量。有什么想法吗?

 for i in $( cat LIST.txt) do 
 sed s/HAL/i/ <~/test/template.txt > new$i.txt
 done

给出的错误是“意外标记 sed 附近的语法错误”,然后给出 sed 行。

【问题讨论】:

  • for i in $(cat foo.txt) 绝对是迭代文件中行的错误方法,开始。请参阅 BashFAQ #001:mywiki.wooledge.org/BashFAQ/001
  • ...也就是说,您不是在说 如何 当它到达 sed 表达式时它会失败,那么我们应该如何知道需要修复什么?
  • ...另外,引用您的扩展:&gt;"new$i.txt" 将在 &gt;new$i.txt 失败的地方成功。
  • ...无论如何——事实上,这个问题无法回答,因为它没有说明具体的错误,而不是“一个问题”和“工作直到”。
  • 您的sed 调用只是简单地将任何出现的“HAL”替换为“i”。也许你的意思是sed -e "s/HAL/${i}/"

标签: bash sed cat


【解决方案1】:

我认为您缺少 for 部分和 do 之间的分号。

for i in $(cat LIST.txt); do 
    sed s/HAL/i/ <~/test/template.txt > new$i.txt
done

这可能更好地重写为(假设LIST.txt 中每行一个单词:

while read i; do
    # Are you sure you don't want to substitute with the variable (`$i`
    # in this case) instead of "i" in the line below?
    sed s/HAL/i/ < ~/test/template.txt > new$i.txt
done < LIST.txt

如果您想替换为$i,您可能希望您的sed 行如下所示:

sed "s/HAL/$i/" < ~/test/template.txt > new$i.txt

【讨论】:

    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2016-07-27
    • 1970-01-01
    相关资源
    最近更新 更多