command line - How do I find the most recent timestamp in directory names in a bash script? - Ask Ubuntu
i have timestamped directories named prefix may vary, , timestamp in handy form yyyymmdd, followed varying suffixes denote chronological order (not in sane fashion). unfortunately, title part of name can include _
character, used field delimiter.
for example:
/collect/mydir_20161102_0a /collect/mydir_20161102_0b /collect/mydir_20161102_0c /collect/mydir_20161102_1 /collect/mydir_20161102_2 /collect/other_dir_20161103_0a /collect/other_dir_20161103_0b /collect/mydir_20161104_0a /collect/mydir_20161104_0b /collect/mydir_20161104_0c /collect/mydir_20161104_1 /collect/mydir_20161104_2
the order of names displayed here chronological order of creation, including suffixes, 0a comes before 0b, , 0s come before 1. there should not incidence of different title prefix same timestamp.
the directories may have been changed or modified since creation, use of ctime , mtime out.
i need output string containing title , timestamp, or without preceding path mydir_20161104
or /collect/mydir_20161104
, must come recent directory. search should not recurse through directory levels.
i avoid parsing ls
too!
might not pretty, , i'm not handling filenames newlines in them:
find collect/ -mindepth 1 | awk -f_ '{print $(nf-1),$nf,$0}' | sort -v | sed -r 's/^([^ ]* ){2}//'
so:
- listing files
find
- adding last 2
_
-delimited fields in filename start of usingawk
- sorting (
-v
- version sort - can handle fields0a
,1
) - removing added part
sed
it made safe filenames containing valid character, i'd have replace awk
sed
that.
my output:
$ find collect/ -mindepth 1 | awk -f_ '{print $(nf-1),$nf,$0}' | sort -v | sed -r 's/^([^ ]* ){2}//' collect/mydir_20161102_0a collect/mydir_20161102_0b collect/mydir_20161102_0c collect/mydir_20161102_1 collect/mydir_20161102_2 collect/other_dir_20161103_0a collect/other_dir_20161103_0b collect/mydir_20161104_0a collect/mydir_20161104_0b collect/mydir_20161104_0c collect/mydir_20161104_1 collect/mydir_20161104_2
of course, parsing ls
. ;)
if need title , timestamp without suffix, reverse sort (sort -vr
) , modify last sed
to:
sed -r 's:.*/::;s/_[^_]*$//;q'
so:
$ find collect/ -mindepth 1 | awk -f_ '{print $(nf-1),$nf,$0}' | sort -rv | sed -r 's:.*/::;s/_[^_]*$//;q' mydir_20161104
and version can handle filenames newlines:
find collect/ -mindepth 1 -print0 | sed -rz 's/(.*)(_[^_]*)(_[^_]*)$/\2\3 &/' | sort -zrv | sed -zr 's:.*/::;s/_[^_]*$//;q'
this uses \0
-delimited lines throughout (-print0
in find
, -z
in sed
, sort
). awk
replaced equivalent sed
command.
Comments
Post a Comment