3

I want to create directory name from a file's modification time. For example, if the file creation or modification time is 03/17/2016 18:00:00 then I want to create a directory named 1703206. I'm using HP-UX.

  • Is perl available? – Jeff Schaller Mar 20 '16 at 23:34
  • Is that directory format DDmmYYHH (day month century hour)? I expected either 2016 (year, no hour) or 2018 (century & hour) – Jeff Schaller Mar 21 '16 at 0:23
1

With only POSIX tools (and HP-UX doesn't have much more than that), this is difficult, because there's no convenient way to get a file's modification time. With ls -l, you need to deal with two cases: recent files with month, day, house and minute, and old files (> 6 months) with month, day and year. (There may be an easier way by crafting an appropriate locale settings but I don't know if that can be done on HP-UX.)

#!/bin/sh
set -e -f
set -- $(LC_ALL=C ls -dlog -- "$1")
# $1=permissions $2=link_count $3=size $4,$5,$6=date_time $7...=filename
case $4 in
  Jan) month=1;;
  Feb) month=2;;
  Mar) month=3;;
  Apr) month=4;;
  May) month=5;;
  Jun) month=6;;
  Jul) month=7;;
  Aug) month=8;;
  Sep) month=9;;
  Oct) month=10;;
  Nov) month=11;;
  Dec) month=12;;
esac
case $6 in
  *:*) # The timestamp is within the last 6 month, so
       # the year is the current or previous year.
    current_month=$(LC_ALL=C date +%Y%m)
    year=${current_month%??}
    current_month=${current_month#????}
    case $current_month in 0*) current_month=${current_month#0};; esac
    if [ $current_month -lt $month ]; then year=$((year-1)); fi;;
  *) year=$6;;
esac
if [ $month -le 9 ]; then month=0$month; fi
day=$5
if [ $day -le 9 ]; then day=0$day; fi
mkdir $year$month$day

If you're using some ancient version of HP-UX where /bin/sh is an old Bourne shell, you may need to replace /bin/sh on the shebang line by the path to a POSIX shell such as ksh.

0

On Linux, if foo is your file

stat -c %Z foo

will give second since epoch (see man stat, you may use %W, %X, %Y, %Z for creation time, access time, modification time, change time)

date --date=@$(stat -c %Z foo) +%m%d%y

will give your format.

SO

 mkdir bar/prefix$(date --date=@$(stat -c %Z foo) +%m%d%y)suffix
  • replace foo, bar, prefix and suffix by actual/desired file name.
  • use quote arround var to avoid funny char.
  • 1
    it's HP-Ux so stat command is not working – Chirag Dhaduk Mar 20 '16 at 10:28
  • well, you originally tag as "linux", can you edit your post ? – Archemar Mar 20 '16 at 10:30

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.