假设我有以下文件:(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的工具和语言来实现这一目标?
答案 0 :(得分:4)
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/'
答案 1 :(得分:3)
csplit
可用于使用正则表达式拆分文本文件。
答案 2 :(得分:2)
这应该有帮助 -
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]