【问题标题】:How can I replace a `---`-separated block with the contents of a text file, using standard Linux tools?如何使用标准 Linux 工具将 `---` 分隔的块替换为文本文件的内容?
【发布时间】:2015-06-29 13:52:14
【问题描述】:

我有一个看起来像这样的文本文件:

Some text here. This text is not replaced.

---

And then a wild block appears!
It has stuff in it that I'm trying to replace.

---

The block is no more. Nothing to replace here. 

还有另一个要插入内容的文本文件:

A multi-
line thing to replace. 
This block is not demarcated 
in the same way
as the other

而我要做的是用文本文件的内容替换----demarcated 块,使其看起来像这样:

Some text here. This text is not replaced.

A multi-
line thing to replace. 
This block is not demarcated 
in the same way
as the other

The block is no more. Nothing to replace here. 

这类似于this question,但我认为这并不适用,因为我正在处理的是一个多行块,而sed 似乎并不擅长于此。 awkruby 或其他东西可以这样做吗?

【问题讨论】:

标签: linux awk sed


【解决方案1】:

未经测试,但如果不完全符合您的要求,将会很接近:

awk '
NR==FNR { file1 = file1 $0 RS; next }
/---/ {
    if (f) {
        printf "%s", file1
    }
    f = !f
    next
}
!f
' file1 file2

【讨论】:

  • 这似乎只打印file2的内容。
  • 您可能在命令行中以错误的顺序放置了输入文件。尝试交换它们。
  • NR==FNR 比较所有文件中读取的行数 (NR) 与当前文件中读取的行数 (FNR) 以及它们是否相等(只有在读取第一个非空文件)然后评估为真。 file1 = file1 $0 RS; next 从读取的第一个文件的内容中构建一个名为 file 的字符串。以/---/ 开头的块打印该字符串而不是file2 中2 个--- 行之间的文本。 !f 调用默认操作,即为不在 --- 对之间的 file2 的每一行打印当前记录。
  • 获取 Arnold Robbins 的《Effective Awk Programming, 4th Edition》一书,并在代码中添加一些 print 语句以进一步调查/了解它的作用。
  • 另外,backreference.org/2010/02/10/idiomatic-awk 中很好地解释了 FNR==NR “技巧”
猜你喜欢
  • 2011-02-11
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2018-10-19
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多