2012年11月21日星期三

split file into files by pattern

http://www.unix.com/shell-programming-scripting/70227-split-file-based-pattern-awk-grep-sed-perl.html


Code:
Buuuu xxx bbb
Kmmmm rrr ssss uuuu
Kwwww zzzz ccc
Roooowwww eeee
Bxxxx jjjj dddd
Kuuuu eeeee nnnn
Rpppp cccc vvvv cccc
Rhhhhhhyyyy tttt
Lhhhh rrrrrssssss
Bffff mmmm iiiii
Ktttt eeeeeee
Kyyyyy iiiii wwww
Rwwww rrrr sssss eeee
Rnnnnn xxxxxxccccc

I like to split the above file into 3 files like below,

file1:

Code:
Buuuu xxx bbb
Kmmmm rrr ssss uuuu
Kwwww zzzz ccc
Roooowwww eeee

file2:

Code:
Bxxxx jjjj dddd
Kuuuu eeeee nnnn
Rpppp cccc vvvv cccc
Rhhhhhhyyyy tttt
Lhhhh rrrrrssssss

file3:

Code:
Bffff mmmm iiiii
Ktttt eeeeeee
Kyyyyy iiiii wwww
Rwwww rrrr sssss eeee
Rnnnnn xxxxxxccccc

Basically the file need to be start with "B" record and start a new file when it come across another "B" record.

###################
awk '/^B/{close("file"f);f++}{print $0 > "file"f}' input.txt

perl -n -e '/^B/ and open FH, ">output_".$n++; print FH;' input.txt

csplit -k input.txt '/^B/' '{99}'

没有评论:

发表评论