I want to split a text file into several ones.
One new file every time the pattern appears.
Example:
The pattern will be PAT
Original file content:
PAT --example html http://askubuntu.com/page01
ABC
DEF
PAT --example html http://askubuntu.com/page02
GHI
JKL
PAT --example html http://askubuntu.com/page03
MNO
PQR
(and so on)
The original file is called original.txt
I would like to get files like so:
$ cat page01.txt
ABC
DEF
$ cat page02.txt
GHI
JKL
$ cat page03.txt
MNO
PQR
(and so on)
Ideally with commands like grep, awk…
The renaming of the files is secondary, but would be a plus to help classifying them.
Thanks in advance.
Best Answer
You could use
awk
with some redirection:The result:
Essentially, for each line beginning with
PAT
, I'm saving the last field (via a field separator of/
) the variablefile
, and then printing every non-empty line (/./
matches lines with at least one character) to the name contained infile
.Note that it's important to close the previous file at each loop to prevent a
"makes too many open files"
error when there's "a lot" of file created.