LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   create multiple files from one file (https://www.linuxquestions.org/questions/linux-newbie-8/create-multiple-files-from-one-file-904657/)

sasanthi 09-23-2011 01:02 PM

create multiple files from one file
 
Hi all,

I have a file called file1.txt like:

KEGG_1
Features selected:
V2 1.00
V6 1.00
V9 1.00
V13 2.00
V36 2.00
KEGG_2
Features selected:
V2 1.00
V3 1.00
V8 1.00
V11 1.00
V45 1.00
V55 1.00
KEGG_3
Features selected:
V9 1.00
V10 2.00
V18 1.00
V29 1.00

And I want to create multiple files like:

KEGG_1.txt
Features selected:
V2 1.00
V6 1.00
V9 1.00
V13 2.00
V36 2.00

KEGG_2.txt
Features selected:
V2 1.00
V3 1.00
V8 1.00
V11 1.00
V45 1.00
V55 1.00

and KEGG_3.txt
Features selected:
V9 1.00
V10 2.00
V18 1.00
V29 1.00

I have written the following perl script:
Code:

#!/usr/bin/perl
use strict;
use warnings;

my $file = shift @ARGV;

                                             
open(IN, $file ) || die "could not open $file\n";

my %answer;
my $regex='KEGG';

#open ouf, ">$regex.txt" or die "Could not open file $regex.txt for output.$!";
foreach my $lines (<IN>) {

    foreach ($lines =~ m/^$regex/) {

            my $key =$lines;
            open (outp, ">$key")  or  die "Could not open file $key for output.";

        if ($lines =~ m/^$regex/ || $lines =~ m/^V/) {         
            print outp $lines;
        }
            close(outp);
     
        }
}
close(IN);

but when I am running it, I am getting the following error:
"Could not open file KEGG_1
for output. at line 27, <IN> line 2538."

could someone help me? I cannot understand why?

thanks a lot!

AlucardZero 09-23-2011 01:17 PM

You aren't removing the newline.

Code:

my $key =$lines;
chomp $key;


Ghostwheel 09-23-2011 01:18 PM

Try adding this before the output line:

touch $key

colucix 09-23-2011 01:54 PM

In addition, may I suggest a simple awk alternative?
Code:

awk '/KEGG/{file=($0 ".txt")}!/KEGG/{print > file}' file1.txt
or a simple bash code:
Code:

#!/bin/bash
while read line
do
  [[ $line =~ "KEGG" ]] && file=$line.txt || echo "$line" >> $file
done < file1.txt


schneidz 09-23-2011 02:02 PM

also in bash
Code:

cat sasanthi.txt | while read line; do if [ "`echo $line | grep KEGG`" ]; then f=$line; else echo $line >> $f.txt; fi; done

sasanthi 09-23-2011 03:19 PM

thanks a lot! :)


All times are GMT -5. The time now is 06:16 PM.