【问题标题】:bash : inexplicable behavior sedbash : 莫名其妙的行为 sed
【发布时间】:2015-09-30 10:16:00
【问题描述】:

我写了一个非常简单的 bash 脚本:

#!/bin/bash

nLine=$(awk '/text_to_parse/{ print NR; exit }' testFile.xml)
echo "LINE = $nLine"
sed -e "${nLine}s/.*/new text/" < testFile.xml
echo 
cat testFile.xml

exit 0

执行返回:

LINE = 8
<Test>
    <Name>First Test</Name>
    <Version>1.0</Version>        
    <Command>new text</Command>
</Test>

<Test>
    <Name>First Test</Name>
    <Version>1.0</Version>        
    <Command>text_to_parse</Command>
</Test>

永远不会应用修改。文件可以修改..

 -rwxrwxrwx 1 root root  290 Jan  1 00:23 testFile.xml

【问题讨论】:

  • 您确定这是您的xml 和您的shell 脚本吗? LINE 应该是 4,你的 sed 调用应该替换整行而不是 text_to_parse,不是吗?

标签: linux bash shell awk sed


【解决方案1】:

你的整个脚本应该被重写为这个命令:

sed -i 's/.*text_to_parse.*/new text/' testFile.xml
cat testFile.xml

您需要在某些 sed 中为 -i 提供一个参数。

【讨论】:

  • 从 OP 的输出来看,我认为他们只想替换 text_to_parse 而不是它周围的东西。
  • 也许,idk 因为他们没有提供示例输入和预期输出,所以我只是将他们的 shell 脚本重写为 sed 脚本。他们可能想要一些完全不同的东西——通过阅读一个没有按照他们想要的方式执行的脚本,总是很难猜出一个脚本应该做什么!
  • 你说得对。感谢您的回复。如果我必须发布新问题,我会考虑您的评论。
【解决方案2】:

不太清楚 Line = 8 是怎么回事。但是如果我正确理解了要求,那就是替换包含文本的第一行。您还可以执行以下操作:
sed -i '/text_to_parse/{s/.*/new text/;:a;n;ba}' testFile.xml
sed -i '0,/text_to_parse/{/text_to_parse/s/.*/new text/}' testFile.xml

【讨论】:

    猜你喜欢
    • 2012-11-14
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2012-03-12
    • 2019-02-04
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多