【问题标题】:split file after a match at the end of the file and keep the match inside file unix在文件末尾匹配后拆分文件并将匹配保留在文件 unix 中
【发布时间】:2020-10-12 11:10:52
【问题描述】:

我有一个包含随机行和关键词END的文件:

line 1
line 2
...
line 23
END
line 25
....
line 40
END

我想根据关键字 END 将其拆分为多个文件,并将其放在每个文件中: 文件 1

line 1
line 2
...
line 23
END

文件 2

line 25
.....
line 40
END

我试过了:

csplit -k file_name '/END/' '{*}' but i do not get the correct output.

【问题讨论】:

    标签: unix awk split csplit


    【解决方案1】:

    向正则表达式添加偏移量 1 以在当前文件中包含匹配的 END。我还添加了^$ 来锚定正则表达式。

    csplit -k file -f file --elide-empty-files '/^END$/1' '{*}'
    
    • -f file 设置输出文件名前缀
    • --elide-empty-files 这是 GNU 扩展,不输出空文件(在本例中为空文件 file02

    输出:

    $ head file0*
    ==> file00 <==
    line 1
    line 2
    ...
    line 23
    END
    
    ==> file01 <==
    line 25
    ....
    line 40
    END
    

    【讨论】:

    • TIL --elide-empty-files 切换。
    【解决方案2】:

    awk

    $ awk '{f= FILENAME"."(c+1); print > f} /^END$/{close(f); c++}' file
    
    $ head file.*
    
    ==> file.1 <==
    line 1
    line 2
    ...
    line 23
    END
    
    ==> file.2 <==
    line 25
    ....
    line 40
    END
    

    边缘情况行为: 如果输入文件为空(无行),则不会生成输出。 如果文件有空行,则将文件的精确副本生成为分区(与没有END 标记或末尾只有一个相同)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 2014-12-12
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      相关资源
      最近更新 更多