How to remove a part of file which has a definite pattern

October 5, 2012 at 11:05:44
Specs: UNIX environment
The filenames are like

%262349.01%_20121001-004253.262349
%0110010051CKwZ_20121001-005722.zip
2012100104190517466_20121001-041916

I need to remove the _YYYYMMDD-hhmmss pattern for each filename and retain the rest

Need a urgent help..please


See More: How to remove a part of file which has a definite pattern

Report •

#1
October 8, 2012 at 18:23:37
I think this problem is too hard for legacy Unix tools so I am using a perl program. I am using a regular expression to find an underscore, an integer string, a dash, and another integer string. It does NOT verify that the strings are valid dates and times:

#!/usr/bin/perl

use strict;
use warnings;
use English;

#my $mydir = "./mydir";
#chdir($mydir) or die "Cannot chdir to $mydir $!";
my $ddate;
my $dtime;

# list the files
open(LS, "ls -1 |") or die "Cannot open ls command \n";
while(<LS>){
   chomp;
   # use regular expression to determine filename with YYYYMMDD-hhmmss
   ($ddate,$dtime) = /_(\d+)-(\d+)/;
   if ( defined $ddate && $ddate ne '' && defined $dtime && $dtime ne '')
      {
      my $dstr = '_' . $ddate . '-' . $dtime;
      my $newfile = $_;
      $newfile =~ s/$dstr//g;
      # rename the file
      my $msg = `mv  $_  $newfile`;
      if ($CHILD_ERROR != 0)
         {
         print "File Creation Error\n";
         exit 1;
         }
      }
   }
close(LS);
print "File move done!\n";



Report •
Related Solutions


Ask Question