0

I need to extract the date part from a file in unix and add +1 day to the date and rename the file with the new date in it.

for ex: sample file name: sample_file_name_01_31_2022_14_01_45_loadid.csv I tried to extract the timestamp using substr which gives 01_31_2022_14_01_45. Now, the new date should be 02_01_2022_14_01_45 and the new file name should be sample_file_name_02_01_2022_14_01_45_loadid.csv

nag
  • 75
  • 5

1 Answers1

0

Given the AIX operating environment, which doesn't have GNU date installed by default (for the handy date -d ... functionality), I'd approach this problem with a perl script. The script below uses fairly common modules that should be available on an AIX system.

The basic idea behind the script is to loop over every given argument (one or more filenames) and:

  1. extract the date/time fields from the filename
  2. convert those fields into seconds-since-the epoch
  3. add one day's worth of seconds
  4. convert that new timestamp into the desired string format
  5. rename the file

I encountered a slight complication while adding error-checking: the timelocal() function will croak (exit the script) if any of the given date/time fields are out of range. Because I wanted to be able to loop over any remaining arguments, I had to wrap that call in a Try-Catch block.

#!/usr/bin/perl -w

use strict;
use POSIX qw(strftime);
use Time::Local qw(timelocal);
use Try::Tiny;

sub rename_a_file {
  my $filename = shift;

  # extract date from filename
  my ($prefix, $month, $day, $year, $hour, $minute, $second, $suffix);

  unless (
    ($prefix, $month, $day, $year, $hour, $minute, $second, $suffix) =
      $filename =~ /^(.*)_(\d{2})_(\d{2})_(\d{4})_(\d{2})_(\d{2})_(\d{2})_(.*)$/
    ) {

      warn "Could not determine a timestamp from ${filename}; skipping\n";
      return undef;
  }

  # local time in seconds-since-the-epoch
  my $t;

  # timelocal will die if any inputs are out of range; catch it
  my $flag = 0;
  try {
    $t = timelocal($second, $minute, $hour, $day, $month - 1, $year - 1900);
  } catch {
    warn "Unable to convert time specification: $_";
    $flag = 1;
  };
  return undef if $flag;

  # add one day's worth of seconds
  $t += 24 * 60 * 60;

  # new timestamp in string format
  my $newdate;
  unless ($newdate = strftime("%m_%d_%Y_%H_%M_%S", localtime $t)) {
    warn "Unable to convert new date to a string format: $!";
    return undef;
  }

  # rename file using new date
  unless (rename $filename, "${prefix}_${newdate}_${suffix}") {
    warn "Unable to rename $filename: $!";
    return undef;
  }
  return 1;
}

my $errors = 0;
for (@ARGV) {
  unless (rename_a_file($_)) {
    warn "Unable to rename: $_\n";
    ++$errors;
  }
}
$errors = 255 if $errors > 255;
exit $errors;
Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38