The UNIX and Linux Forums  
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #1 (permalink)  
Old 07-16-2008
figaro figaro is offline
Registered User
  
 

Join Date: Jan 2007
Posts: 267
Perl: parsing variables

I have the following script:
Code:
#!/usr/bin/perl -w

@files = <*.csv>;
foreach $file (@files) {
  open(FH, $file);
  my @dt = split(/_|.csv/, $file);
  while (<FH>) { 
    chomp;
    print $dt[1] . $dt[2] . ",$_\n";
  }
  close(FH);
}
This script reads in all csv files in the current directory and prints the date, time and complete contents to screen.

A filename is composed of a name, a date, a time and a suffix ".csv". So a filename could be foo_20080909_120345.csv
Upon running this, the @dt array holds:
- $dt[0] = "foo"
- $dt[1] = 20080909
- $dt[2] = 120345

So line 9 (print $dt[1] . $dt[2] . ",$_\n") yields lines of the following:
"20080909 120345,[...rest of the record...]"
where it should yield:
"2008-09-09 12:03:45,[...rest of the record...]"

How do I enter dashes ("-") and colons (":") at the right places without using contrived code such as:
substr($dt[1], 0, 4) . "-" . substr($dt[1], 4, 2) . "-" . substr($dt[1], 6, 2)
and that is just for the date.

Thanks in advance