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.

- 829,060
-
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 00:23
2 Answers
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.

- 67,283
- 35
- 116
- 255

- 829,060
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
andsuffix
by actual/desired file name. - use quote arround var to avoid funny char.

- 829,060

- 31,554