Bash script to send lines of file to new file based on Regex

I have a file that looks like this:

cat includes
CORP-CRASHTEST-BU
e:\crashplan\
CORP-TEST
/usr/openv/java
/usr/openv/logs
/usr/openv/man
CORP-LABS_TEST
/usr/openv/java
/usr/openv/logs
/usr/openv/man

What I want to do is make three new files with just those selections. So the three lowercase lines under CORP-CRASHTEST-BU would output to another file, then CORP-TEST would also output the following three lowercase lines to another file. I have tried to use arrays, but if I have to provide numbers to identify the arrays it would be hard since it is not just the file above but other files that I want to perform this operation on. I need a a script that would send anything underneath a line that contains capital letters to another file. If anyone has a suggestion on how to start on this, it would be appreciated. I have not started on it yet, so I'm just asking for a general idea.

There's no three lines under CORP-CRASHTEST-BU. Please carefully match your written specification with your sample data. Nevertheless, try

$ awk '$0==toupper($0){fn=$0} {if (fn) print >fn}' file

Not much different approach:

awk '$0~/[[:upper:]]/{if(F) close(F);F=$0;next}{print > F}' includes
1 Like

The difference is that Yoda's approach would fire a new file name if $0 contains one single upper case char anywhere, while the other needs an all upper $0. The specification is a bit vague in this point...

1 Like

I found what I needed after checking your examples:

gawk '/[A-Z0-9.-]$/{x="F"++i;}{print > x;}' 

This works like a charm and I got four files F1 F2 F3 and F4 which are correctly split as I desired!

Without your help I never would have looked into this and your examples have encouraged me to learn even more about awk/gawk/nawk.