根据特定的模式独立单的文本文件分割成多个文件(Separate single text file i

2019-07-29 15:00发布

假设我有以下文件:(Song.txt)

Song one
bla bla bla bla 
bla bla bla bla bla
Song two
yaya ya yaa 
blaaa bla bla blaaaaa
Song three
bla bla bla

我想将这个文件分为三个文件是这样的:

第一个文件名应该是Song_1.txt

Song One
bla bla bla bla 
bla bla bla bla bla

第二个文件名应该是Song_2.txt

Song two
yaya ya yaa 
blaaa bla bla blaaaaa

第三个文件名应该是Song_3.txt

Song three
bla bla bla

我怎么能这样用awk,grep的,PERL,Python和/或任何基于UNIX的工具和语言吗?

Answer 1:

这应该帮助 -

gawk -v RS="Song" 'NF{ print RS$0 > "Song_"++n".txt" }' Song.txt

测试:

[jaypal:~/Temp] cat Song.txt 
Song one
bla bla bla bla 
bla bla bla bla bla
Song two
yaya ya yaa 
blaaa bla bla blaaaaa
Song three
bla bla bla

[jaypal:~/Temp] gawk -v RS="Song" 'NF{ print RS$0 > "Song_"++n".txt" }' Song.txt

[jaypal:~/Temp] ls -l S*
-rw-r--r--  1 jaypalsingh  staff  113 28 May 17:55 Song.txt
-rw-r--r--  1 jaypalsingh  staff   47 28 May 18:06 Song_1.txt
-rw-r--r--  1 jaypalsingh  staff   45 28 May 18:06 Song_2.txt
-rw-r--r--  1 jaypalsingh  staff   24 28 May 18:06 Song_3.txt

[jaypal:~/Temp] cat Song_1.txt 
Song one
bla bla bla bla 
bla bla bla bla bla

[jaypal:~/Temp] cat Song_2.txt 
Song two
yaya ya yaa 
blaaa bla bla blaaaaa

[jaypal:~/Temp] 


Answer 2:

csplit Song.txt --elide-empty-files --prefix=Song_ --suffix-format='%1d.txt' '/Song one/' '/Song two/' '/Song three/'

要么

csplit Song.txt -z -f Song_ -b '%1d.txt' '/Song one/' '/Song two/' '/Song three/'


Answer 3:

csplit可以用于使用正则表达式来分割文本文件。



文章来源: Separate single text file into multiple files based on certain pattern