如何将 linux 文件拆分为多个文件?
How can I split my linux file into multiple files?
我想将一个文件拆分成多个文件。我的输入是
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
End of Report
$
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
$
Report : XYZ Page: 2
ABC
DEF
GHI
JKL
End of Report
$
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
End of Report
$
输出应该是:
文件 1
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
End of Report
$
文件 2
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
$
Report : XYZ Page: 2
ABC
DEF
GHI
JKL
End of Report
$
文件 3
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
End of Report
$
我试过了
awk '{print [=5=] "Report :"> "/tmp/File" NR}' RS="END OF" test.txt
和
推荐
用过
awk '/^Report/{filename++} {f="File"filename; if(lf != f) {close(lf); lf=f}} {print > f}' test.txt
但我没有得到合适的输出。
如有任何指导,我们将不胜感激。
试试这个:
awk -v i=1 '{print > "File"i; if(/End of Report/)i++}' InputFile
虽然它会生成 1 个额外的文件,但我希望这不会成为问题。
没有额外的文件:
awk -v i=1 '{print > "File"i; if(/End of Report/)i++} END{system("rm File"i)}' InputFile
解释:
脚本将开始将每一行转发到 File 1 (since i=1 set initially)
。在打印每个 End of Report
、i is incremented
之后,从下一行开始,内容将被转发到 File2
等文件内容的其余部分。将生成一个 extra file
,其中包含最后 End of Report
行之后的文件内容,如果有问题,可以轻松删除。
试试这个,我稍微修改了一下
csplit input.txt '/Page: 1$/' '{*}'
另一种 awk 方式
awk '{print >"File"(i+=/Page: 1[^1-9]*/)}' file
我想将一个文件拆分成多个文件。我的输入是
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
End of Report
$
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
$
Report : XYZ Page: 2
ABC
DEF
GHI
JKL
End of Report
$
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
End of Report
$
输出应该是:
文件 1
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
End of Report
$
文件 2
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
$
Report : XYZ Page: 2
ABC
DEF
GHI
JKL
End of Report
$
文件 3
Report : XYZ Page: 1
ABC
DEF
GHI
JKL
End of Report
$
我试过了
awk '{print [=5=] "Report :"> "/tmp/File" NR}' RS="END OF" test.txt
和
推荐
用过
awk '/^Report/{filename++} {f="File"filename; if(lf != f) {close(lf); lf=f}} {print > f}' test.txt
但我没有得到合适的输出。
如有任何指导,我们将不胜感激。
试试这个:
awk -v i=1 '{print > "File"i; if(/End of Report/)i++}' InputFile
虽然它会生成 1 个额外的文件,但我希望这不会成为问题。
没有额外的文件:
awk -v i=1 '{print > "File"i; if(/End of Report/)i++} END{system("rm File"i)}' InputFile
解释:
脚本将开始将每一行转发到 File 1 (since i=1 set initially)
。在打印每个 End of Report
、i is incremented
之后,从下一行开始,内容将被转发到 File2
等文件内容的其余部分。将生成一个 extra file
,其中包含最后 End of Report
行之后的文件内容,如果有问题,可以轻松删除。
试试这个,我稍微修改了一下
csplit input.txt '/Page: 1$/' '{*}'
另一种 awk 方式
awk '{print >"File"(i+=/Page: 1[^1-9]*/)}' file