0

i am using awk command to get creation date of file and from that i m fetching day,month and year but for 1-9 digit i am getting output like 2016041 but i want output 20160401.

D=$(ls -ltr $line | awk '{print $7}') 

M=$(ls -ltr $line | awk '{print $6}')

 Y=$(date +"%Y")

TEMP2="$Y$M$D"
  • stat is not possible because of HP-UX – Chirag Dhaduk Apr 10 '16 at 19:52
  • There is no creation date. You're retrieving last modification date. – roaima Apr 10 '16 at 20:23
  • Agree - but OP probably wants what he sees :-) – Thomas Dickey Apr 10 '16 at 20:26
4

Doing this properly from ls is awkward because the date format changes with the age of the files. Furthermore, the computation for $M is suspect since ls normally returns a name for the month rather than a number. Presumably OP is using the date command to attempt to work around the differences in ls date format, but that means that all of the files would get the same value for a year.

However, OP's question is focused on leading zeros. That part is easy in awk:

D=$(ls -ltr $line | awk '{printf "%02d", $7}')
M=$(ls -ltr $line | awk '{printf "%02d", $6}')
Y=$(date +"%Y")

If I had to do this on HPUX, I would look into using Perl (which is preinstalled), since that can avoid the problems with ls and date format.

Here is a quick example (man perlfunc is where to start):

#!/usr/bin/perl -w

use strict;

for my $n ( 0 .. $#ARGV ) {
    my (
        $dev,  $ino,   $mode,  $nlink, $uid,     $gid, $rdev,
        $size, $atime, $mtime, $ctime, $blksize, $blocks
    ) = stat( $ARGV[$n] );
    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
      localtime($mtime);

    # printf "%s:", $ARGV[$n];
    printf "%04d%02d%02d", 1900 + $year, 1 + $mon, $mday;

    # printf "\n";
}
1;

I checked the script with the two printf statements uncommented, and looking at sample files. You would call this script with just one filename (for multiple filenames, the lack of formatting would be a nuisance).

  • Hi, can you please tell me how can i use perl to get date ? – Chirag Dhaduk Apr 10 '16 at 20:06
  • @ChiragDhaduk that's what this answer shows you! – roaima Apr 10 '16 at 20:23
0

Leading zeros may also be added using printf. It seems to be available in HP-UX.

D=$(ls -ltr $line | awk '{print $7}') 
M=$(ls -ltr $line | awk '{print $6}')
Y=$(date +"%Y")
TEMP2="`printf '%02d%02d%04d' $D $M $Y`"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.