如何将我的文件拆分成多个文件?

How can I split my file into multiple files?

我想将一个文件拆分成多个文件。我的输入是

Report : 1
ABC
DEF
GHI
JKL
   End of Report
$
Report : 2
ABC
DEF
GHI
JKL
$
Report : 2
ABC
DEF
GHI
JKL
   End of Report  
$
Report : 3
ABC
DEF
GHI
JKL
   End of Report
$

输出应该是:

文件 1

Report : 1
ABC
DEF
GHI
JKL
   End of Report
$

文件 2

Report : 2
ABC
DEF
GHI
JKL
$
Report : 2
ABC
DEF
GHI
JKL
   End of Report  
$

文件 3

Report : 3
ABC
DEF
GHI
JKL
   End of Report
$

我试过了

awk '{print [=14=] "Report :"> "/tmp/File" NR}' RS="END OF" test.txt

但我没有得到适当的输出。

如有任何指导,我们将不胜感激。

你可以试试

$awk '/^Report/{filename++} {print > "FILE"filename}' input

测试

$awk '/^Report/{filename++} {print > "FILE"filename}' input

$ cat FILE1
Report : 1
ABC
DEF
GHI
JKL
   End of Report
$

$ cat FILE2
Report : 2
ABC
DEF
GHI
JKL
$
Report : 2
ABC
DEF
GHI
JKL
   End of Report
$

$ cat FILE3
Report : 3
ABC
DEF
GHI
JKL
   End of Report
$

它的作用

  • /^Report/ 模式适用于以 Report 开头的行 同一行第三列中的数字是必须用作文件名的文件名接下来几行

  • {filename++} 将文件名值增加一个

  • {print > "FILE"filename} 将每一行打印到文件中。

    例如,如果 filename1 那么这一行与

    相同
    print > FILE1
    

    这是输出重定向,与bash等中使用的相同

    注意 print 没有属性,如果缺少属性,awk 将打印整条记录。这与写 print [=20=] > "FILE"filename

  • 相同

试试这个,

csplit input.txt '/End of Report$/' '{*}'

说明

  • csplit 是一个 UNIX 实用程序,用于将文件拆分为两个或多个由上下文行确定的较小文件。

  • input.txt 这是要拆分的文件。

  • '/End of Report$/' 具体模式如 "End of Report" .

  • '{*}'选项表示整个文件。

这是另一个 awk 答案:

awk '/^Report/{n=} {print > "File"n}' input

这类似于 nu11p01n73R 的回答,但使用每个 Report 行的第三个字段来确定文件编号。

  • /^Report/匹配行时,设置n</code>。</li> <li>创建文件名时使用<code>n将每一行打印到

如果您有大量这样的块,您可能需要关闭文件并改为使用此命令:

awk '/^Report/{f="File"; if(lf != f) {close(lf); lf=f}} {print > f}' input
  • /^Report/匹配行时,创建一个文件名f
  • 如果 lf(最后一个文件名)与 f 不匹配,首先尝试关闭 lf,然后重置 lf。在未设置 lf 时调用 close() 是安全的
  • 将每一行打印到 f