user3483833
user3483833

Reputation: 1

perl code for splitting a single file by matching charater into multiple files

i want to split a large data file into multiple files where ever it matches a '^' character.

#!/usr/bin/perl -w  
use strict;  
print "enter the data file name";  
chomp( my $a=<STDIN> );  
open (<READ>,"$a")| "error";  
while ($line=<READ>)  
 {  
  my @array=split("        ",$line) unless ^ ;  

after splitting of the data file. A total of 23 files will be created

Upvotes: 0

Views: 133

Answers (4)

use strict;

open(FILE,'AUTOSAR.txt');
local $/;
my $var = <FILE>;
my @arr = split('\^',$var);
my $i=0;

foreach (@arr) {
    $i++;
    open(FILE1,">$i.txt");
    print FILE1 $_;
    close FILE1;
}

close FILE;

Upvotes: 0

pedroivo000
pedroivo000

Reputation: 88

Here's a slight different answer from saiprathapreddy.obula's:

use warnings;
use strict;

my ($file) = @ARGV;

open(my $input, "<$file");

local $/ = "^";

my $i = 0;

while(<>){
    chomp;

    $i++;

    open(my $output, ">file$i.txt");
    print $output "$_"; 
}

Upvotes: 1

Mark Nodine
Mark Nodine

Reputation: 163

Here is a cleaned up and tested version of the program of saiprathapreddy.obula.

use strict;
use warnings;

open(FILE,'AUTOSAR.txt');

local $/;
my $var = <FILE>;
close FILE;

my @arr = split('\^',$var);
my $i=0;

foreach (@arr) {
    $i++;
    open(FILE1,">$i.txt");
    print FILE1;
    close FILE1;
}

Upvotes: 0

Syam Kumar
Syam Kumar

Reputation: 21

$,="";
$"="";
my $i=1;
open OUT ,">DATA_${i}.txt";
while(<>){
    chomp;
    my @F=split(/\^/);
    if(@F==1){
            print OUT $_,"\n";
    }
    elsif(@F>1){
            $i++;
            close OUT;
            open OUT ,">DATA_${i}.txt";
            print OUT "@F[1..$#F] \n";
    }
}
close OUT;

Upvotes: 0

Related Questions