【问题标题】:Substitute string with file content in sed用 sed 中的文件内容替换字符串
【发布时间】:2018-11-01 19:40:15
【问题描述】:

我在尝试用 sed 进行以下替换时迷路了:

@编辑:捕捉我的问题的全部复杂性, 我后来添加了文件名包含在变量中的事实。 因此,解决方案可能会直接使用文件名。

给定一个变量 I='insert.txt':

'插入.txt':

Text I wanna skip.

This is text to insert containing
spaces and new lines

给定一个变量 M='toModify.txt':

'toModify.txt':

Insert the new text: here.

我想用内容替换 $M 中的“这里” $I:

Insert the new text: This is text to insert containing
spaces and new lines.

我试过了:

sed -e "s/here/$(tail -n2 $I | sed -e 's/ /\\ /g' | tr '\n' '\\n')/" $M

有错误: sed 未终止的 `s' 命令

问题是在不终止 s 命令的情况下我没有得到空格和换行符。

有什么办法吗?

【问题讨论】:

  • 请将该示例输入的所需输出添加到您的问题中。
  • 非常类似于Use the contents of a file to replace a string using SED。有一个很好的区别,但这个答案可能会对你有所帮助。
  • insert.txt中,如何区分要跳过的文本和要插入的文本?

标签: bash awk sed


【解决方案1】:

tr 不能用两个字符替换一个字符。无论如何,逃离各个空间是没有意义的。立即错误的原因是您最终也转义了最后的斜线:

linux$ tail -n2 "$I" | sed -e 's/ /\\ /g' | tr '\n' '\\n'
This\ is\ text\ to\ insert\ containing\spaces\ and\ new\ lines\/

无论如何,转义空格是没有意义的。我猜你想要这样的东西:

linux$ sed '1,2d;$!s/$/\\/' "$I"
This is text to insert containing\
spaces and new lines

我们删除第 1 行和第 2 行;然后在除最后一个换行符之外的每个换行符之前添加一个反斜杠。

linux$ sed -e "s/here/$(sed '1,2d;$!s/$/\\/' "$I")/" "$M"
Insert the new text: This is text to insert containing
spaces and new lines.

这是sed 的一个细节,它不是完全可移植的。但以上内容适用于我在 Linux 和 MacOS 上。 (请注意,您可能需要 set +H 来禁用 csh 样式的历史扩展又名 -bash: !s/$/\\/': event not found 错误)。

【讨论】:

  • 谢谢,解决了我的问题!你能解释一下 \ 实际上在做什么吗?它是否被解释为新行之前的延续字符?
  • 是的,它转义了换行符,所以sed 知道文本在下一行继续。
【解决方案2】:

你可以使用这个awk:

awk 'BEGIN{prs=RS; RS=""; getline s < "insert.txt"; RS=prs}
{gsub(/here/, s)} 1' toModify.txt

Insert the new text: This is text to insert containing
spaces and new lines.

【讨论】:

    【解决方案3】:

    使用 Perl 单行代码

    > cat insert.txt
    This is text to insert containing
    spaces and new lines
    > cat toModify.txt
    Insert the new text: here
    > export I=insert.txt
    > export M=toModify.txt
    > perl -ne 'BEGIN{$x=qx(cat $ENV{M});$x=~s/here/qx(cat $ENV{I})/e; print $x;exit }'
    Insert the new text: This is text to insert containing
    spaces and new lines
    
    >
    

    【讨论】:

      猜你喜欢
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      相关资源
      最近更新 更多