0

please help me with this. I have file of following pattern

ABC x  
bla bla bla  
bla bla  
bla  
XYZ  
ABC y   
bla bla bla  
bla bla  
bla bla bla  
XYZ  

ABC z  
bla bla bla
XYZ

I need output in file x.txt

ABC x  
bla bla bla  
bla bla  
bla    
XYZ  

and

ABC y   
bla bla bla  
bla bla  
bla bla bla  
XYZ 

in y.txt and so on for rest of patterns

Jotne
  • 40,548
  • 12
  • 51
  • 55
Vikas
  • 39
  • 1
  • 2

5 Answers5

2

Some like this:

awk '/ABC/ {close(f".txt");f=$2} {print >f".txt"}' file

This test if line starts with ABCand then set output file name to value in $2

Eks

cat y.txt
ABC y
bla bla bla
bla bla
bla bla bla
XYZ

EDIT: added close() to awk to close open file so it does not run out of space if it creates many files

Jotne
  • 40,548
  • 12
  • 51
  • 55
  • To avoid printing empty lines into these files, you can use `$0{print >f".txt}`, so that if `$0` is empty, the condition won't be matched. – fedorqui Oct 21 '13 at 08:25
  • That may be good and may be bad to do. If there are space between start end and end pattern, they are lost too. – Jotne Oct 21 '13 at 08:40
0

Well, put all Input into one Array, walk through that with Regex until you find ABC something, open something.txt as Output, continue through your Array printing the lines to Output until you find XYZ and move on.

I assume you know how to write Perl.

DeVadder
  • 1,404
  • 10
  • 18
0

How about:

my $fh;
open my $fh_in, '<', "input_file" or die "unable to open 'input_file: $!";
while (<$fh_in>) {
    chomp;
    if (/^ABC \w+/../XYZ/) {
        if (/^ABC (\w+)/) {
            open $fh, '>', "$1.txt" or die "unable to open '$1.txt': $!";
        }
        print $fh $_,"\n";
    }
}
Toto
  • 89,455
  • 62
  • 89
  • 125
0

You can do it using sed as shown below:

sed -n '/ABC x/,/XYZ/p' file > x.txt

If you know all the patterns, you can use a loop:

for i in x y z
do
   sed -n "/ABC $i/,/XYZ/p" file > "$i".txt
done
dogbane
  • 266,786
  • 75
  • 396
  • 414
0
awk '/ABC/{name="file "$2".txt";}{print >name}' your_file
Vijay
  • 65,327
  • 90
  • 227
  • 319