MacOS Терминал найти самый последний файл в каталоге

1086
tjt263

Я пишу (как я думал, это будет) небольшая быстрая bashфункция для определения самых последних фотографий, импортированных в стандарт Apple Photos.appот DSLR.

Пока это выглядит примерно так:

find ~/Pictures/Photos\ Library.photoslibrary/Masters -type f

Довольно просто Как таковой, он перечисляет всю библиотеку импортированных фотографий. Моим первым инстинктом было просто | tail -n 1, но файлы не перечислены ни в каком заметном порядке.

Я подумал | sort -V, но нередко имена файлов (т.е. IMG_0123.CR2) выходят из строя.

К вашему сведению: эта версия BSD findне поддерживает -printfопцию, найденную в версии GNU.

0
Команда листинга: `ls -lt dir | head -n 1` получает первый файл, но я не знаю формат файла, т.е. * .jpg, который использует фотография, поэтому не может быть более явным Mark 6 лет назад 0

2 ответа на вопрос

1
David Lindegren

Я нашел этот ответ на похожий вопрос, Заказать Поиск результатов по дате модификации .

В вашем случае это должно быть что-то вроде:

find ~/Pictures/Photos\ Library.photoslibrary/Masters -type f -print0 | xargs -0 ls -tl 

Более подробную информацию о том, как он взаимодействует, можно найти по ссылке выше.

0
jimtut

Сохраните этот скрипт на Perl где-нибудь в вашем поиске $ PATH, chmodчтобы сделать его исполняемым, а затем просто запустите его. Он предложит вам несколько вариантов, включая сортировку по имени или дате. Это старый сценарий, который я написал несколько лет назад, не слишком много его ломайте; это работает!

#!/usr/bin/perl -w  # This script finds files or folders that have been modified "recently" # (as determined by the timeframe specified in the arguments). # Just run the script to get the full usage instructions.  use strict; use File::Find; use Config;  my $time; my $units; my $dir; my $order = "time"; my @validUnits = qw(sec min hours days); my @results; my %results;  if ($#ARGV < 1) { print "\nUSAGE: $0 [-f] <time> <units> [dir]\n\n"; print "Search for recently modified files or folders located\nin (or under) dir (which is \".\" if not specified).\n"; print "\nResults are sorted by timestamp, in ascending order, unless the '-f' option is used\n"; print "to specify sorting by filename.\n"; print "\nPlease enter the time (just a number): "; $time = <>; chomp $time; print "Please enter the units (@validUnits): "; $units = <>; chomp $units; print "Please enter the directory: [.] "; $dir = <>; chomp $dir; if ($dir eq "") { $dir = "." } print "Sort order (file or time): [time] "; $order = <>; chomp $order; if ($order eq "") { $order = "time" } print "\n"; } else { if ($ARGV[0] eq "-f") { $order = "filename"; shift; } $time = shift; $units = shift; if ($#ARGV > -1) { $dir = shift; } else { $dir = "."; } }  # Check the time entered. if (!($time) || !($time =~ m/^[0-9]*$/)) { print "You must enter an integer for the length of time.\n"; exit 1; }  # Check the units entered. my $validUnits = grep m/$units/, @validUnits; if (!($units) || !($validUnits)) { print "You must use one of the valid units: @validUnits\n"; exit 1; }  if ("min" eq $units) { $time *= 60 } if ("hours" =~ m/$units/) { $time *= 60 * 60 } if ("days" =~ m/$units/) { $time *= 60 * 60 * 24 } my $now = time(); my $then = $now - $time;  find ( sub { # If you can't get the mtime for a file, it's probably a dead link. # Set $mtime back to "0", to remove this dead link from consideration. # NOTE: all links are resolved, so $mtime reflects the mtime of the # link target, not the link itself. my $mtime = (stat)[9] || "0"; if ($mtime > $then) { # If the $mtime is more recent than the target ($then), # add the mtime to the %results hash, # keyed by filename (w/ relative path) $results{$File::Find::name} = $mtime; } }, $dir );  # Get all the keys (filenames) of the %results hash. # If we're sorting by "time", re-sort @results by the timestamp. @results = sort keys %results; if ($order eq "time") { @results = sort { $results{$a} <=> $results{$b} } @results; }  foreach my $key (@results) { # If we're sorting by "time", print the time first, followed by filename. # Else, print filename first, followed by time. if ($order eq "time") { print localtime($results{$key}) . ": $key\n"; } else { print "$key: " . localtime($results{$key}) . "\n"; } }  if ($Config{'osname'} eq "MSWin32") { print "\nPress RETURN to exit.\n"; <>; }