Reputation: 1
I have a file with is like this
PATTERN1abcdef_abcd_ab
a
b
PATTERN2azerty_az_aze
c
d
and I need to split it into smaller files like these: PATTERN1abcdef_abcd_ab.txt, which contains:
PATTERN1abcdef_abcd_ab
a
b
and PATTERN2azerty_az_aze.txt, which contains:
PATTERN2azerty_az_aze
c
d
I found this perl command, which is working fine:
perl -n -e '/^PATTERN/ and open FH, ">output_".$n++; print FH;' inputfile.txt
except it does not rename the output files with the string containing the pattern. (the files are output_1. for example)
EDIT: Sorry, I made a mistake, the string containing the PATTERN should not be removed from output text files, AND should be the file name.
Upvotes: 0
Views: 243
Reputation: 33
If you are trying to get the values to get put into files named PATTERN1(ie that match your pattern). Then you will want to capture the name in your regex and use it as part of your file name.
perl -n -e '/^(PATTERN\d)/ and open(FH, "> $1.txt")and next; print FH;' inputfile.txt
Notice I am capturing the pattern inside the () and $1 will hold the value of our match. I also added a next after file opening, otherwise the match would also be included inside the file.
Upvotes: 1
Reputation: 898
Try this:
perl -n -e '/^PATTERN.*/ and open FH, "$&.txt"; print FH;' inputfile.txt
Upvotes: 1