【问题标题】:substitute several lines in a file with lines from another file用另一个文件中的行替换文件中的几行
【发布时间】:2014-12-03 00:49:52
【问题描述】:

我有两个文件(A.txt 和 B.txt):

A.txt:

  many lines of text
  marker
  A1  A2  A3
  A4  A5  A6
  ...
  ...     AN
  many line of text

B.txt:

  some text
  B1  B2  B3
  B4  B5  B6
  ...
  ...     BN

我想将 A.txt 中的 A1 - AN 块替换为 B.txt 中的 B1 - BN。
请求的结果是:

  many lines of text
  marker
  B1  B2  B3
  B4  B5  B6
  ...
  ...     BN
  many line of text

我知道如何找到 A 块:

grep -n "marker" A.txt |cut -f1 -d:

我知道如何获得B块:

sed -n '2,+6p' B.txt

我什至可以编写一个类似以下内容的脚本:

for ...
var=$(sed -n '2p' B.txt)
sed -i "34s/.*/$var/" A.txt

但我正在寻找简单而优雅的东西

【问题讨论】:

  • 你能确定需要被替换的行(在A.txt中)还是只需要计算它们? B.txt 的那几行呢?
  • 无法通过内容来判断,只能从内容开始定位,然后计数。
  • 是 AN/BN 始终是一行的最后一个字段,A1 和 B1 始终是第一个吗?
  • A1 ... AN, B1...BN 代表双精度值

标签: bash sed


【解决方案1】:
  • 你可以开始获取B.txt的过滤后的内容了:

     sed -n '/B1/,$p' B.txt
    
  • 然后您可以在 A.txt 中的 marker 之后附加 r command

     sed "/marker/r"<(sed -n '/B1/,$p' B.txt) A.txt
    
  • 然后你可以在 A.txt 中从 A1AN 删除:

     sed "/A1/,/AN/d" A.txt
    

总和

sed -e "/marker/r"<(sed -n '/B1/,$p' B.txt) -e "/A1/,/AN/d" A.txt

示例

$ sed -e "/marker/r"<(sed -n '/B1/,$p' B.txt) -e "/A1/,/AN/d" A.txt
  many lines of text
  marker
  B1  B2  B3
  B4  B5  B6
  ...
  ...     BN
  many line of text

【讨论】:

    【解决方案2】:

    如果我理解正确,并且您事先知道块的长度,就会想到这样的事情:

    START=$(grep -n "marker" A.txt | cut -f 1 -d:)
    
    # Note: one more here than you want to skip, since tail and head both
    # take numbers to mean including the line specified. The sed line below
    # generates seven lines of output, so 8 here.
    END=$(($START + 8))
    
    head -n $START A.txt
    sed -n '2,+6p' B.txt
    tail -n +$END A.txt
    

    否则,您可以使用另一个 grep 语句来查找替换块中的最后一行,并以同样的方式进行。

    编辑:原始代码中存在(某种)符号错误。需要 +$END 而不是 -$END。

    【讨论】:

      【解决方案3】:

      只要 A1/B1 是第一个字段并且 BN/AN 是最后一个字段,此 awk 应该适用于任何大小的块

      awk '$1=="B1"{x=1}x{ss=ss?ss"\n"$0:$0}$NF=="BN"{x=0}
           $1=="A1"{y=1}$NF=="AN"{y=0;$0=ss}ARGIND==2&&!y' B.txt A.txt
      

      输出

        many lines of text
        marker
        B1  B2  B3
        B4  B5  B6
        ...
        ...     BN
        many line of text
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-20
        • 1970-01-01
        • 2019-07-26
        • 2017-01-12
        • 2014-02-03
        • 1970-01-01
        • 2021-04-27
        • 2021-01-28
        相关资源
        最近更新 更多