Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 404
  • Last Modified:

Split a single file into 4 separate files one for each column of data using perl or shell

If I have a file that looks like this below with any number of rows. I want to create 4 files from the sample input file. It would simply keep the date & timestamp then a single column corresponding to the new file name for each file. The new files with have 3 columns of data each. The date, timestamp, & column of data.

/path1/inputfile.txt
08-14-2011 00:00:00 0 30 0 23
08-15-2011 00:00:00 1 10 9 12
08-19-2011 00:00:00 0 07 0 18
08-20-2011 00:00:00 0 13 0 11

/path2/outputfile1.txt
08-14-2011 00:00:00 0
08-15-2011 00:00:00 1
08-19-2011 00:00:00 0
08-20-2011 00:00:00 0

/path2/outputfile2.txt
08-14-2011 00:00:00 30
08-15-2011 00:00:00 10
08-19-2011 00:00:00 07
08-20-2011 00:00:00 13

/path2/outputfile3.txt
08-14-2011 00:00:00 0
08-15-2011 00:00:00 9
08-19-2011 00:00:00 0
08-20-2011 00:00:00 0

/path2/outputfile4.txt
08-14-2011 00:00:00 23
08-15-2011 00:00:00 12
08-19-2011 00:00:00 18
08-20-2011 00:00:00 11
0
libertyforall2
Asked:
libertyforall2
  • 2
2 Solutions
 
jeromeeCommented:
Try this for size:

use strict;
use FileHandle; 
my @fds;
while( <> ) {
   chomp;
   my @fields = split;
   if( $. == 1 ) {
      foreach my $field (2..$#fields) {
	 my $fdn = $field-1;
	 my $filename =  "/tmp/fill_$fdn.txt";
	 my $fd = FileHandle->new("> $filename") || die "Can't open $filename: $!\n";
	 $fds[$field-1] = $fd ;
	 print "Opened $filename\n";
      }
   }
   foreach my $field (2..$#fields) {
      my $fd = $fds[$field-1];
      print( $fd "@fields[0,1] $fields[$field]\n");
   }
}

Open in new window

0
 
jeromeeCommented:
run it as:
 perl /path/script.pl  /tmp/data.txt
0
 
Carl BohmanCommented:
Or, if you like one-liners:
perl -ne 'BEGIN{foreach $n(1..4){open(my $F,">/path2/outputfile$n.txt"); $Files[$n]=$F}}@S=split;foreach $n(1..4){print {$Files[$n]} join(" ", @S[0,1,$n+1]), "\n"}' /path1/inputfile.txt

Open in new window

0
 
libertyforall2Author Commented:
One liner worked great!
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now