Find the last modified file in the directory with a space

I found and configured this script to find the last modified file in the directory recursively. It is broken only when there is a space in the directory name. Can someone help me tweak the script so that it also read directories with space? S

for i in *; do find $i -type f | perl -ne 'chomp(@files = <>); my $p = 9; foreach my $f (sort { (stat($a))[$p] <=> (stat($b))[$p] } @files) { print scalar localtime((stat($f))[$p]), "\t", $f, "\n" }' | tail -1 done 
+4
source share
5 answers

Quote corrects everything.

 find "$i" -type f 

In addition, you do not need tail . Just replace $a and $b and exit after printing. A.

 find $i -type f | perl -lne 'chomp(@files = <>); my $p = 9; foreach my $f (sort { (stat($b))[$p] <=> (stat($a))[$p] } @files) { print scalar localtime((stat($f))[$p]), "\t", $f; exit }' 

And -l (the letter "ell") adds new lines for you when printing. A.

Edit:

There is really no need for a loop:

 find -type f | perl -lne 'chomp(@files = <>); my $p = 9; @files = sort { (stat($b))[$p] <=> (stat($a))[$p] } @files; print scalar localtime((stat($files[0]))[$p]), "\t", $files[0]' 
+2
source

Perl? you don’t have bash and like to write long lines of code ?; -)

 find . -type f -printf '%T+ %p\n' | sort -r | head -n1 
+3
source

Writing it all in Perl seems less messy

 perl -MFile::Find -e 'find(sub{@f=((stat)[9],$File::Find::name) if -f && $f[0]<(stat)[9]},".");print "@f")' 
+1
source

Since you only work with the current directory, you can do this with only one command:

 find . -type f | perl -ne 'chomp(@files = <>); my $p = 9; foreach my $f (sort { (stat($a))[$p] <=> (stat($b))[$p] } @files) { print scalar localtime((stat($f))[$p]), "\t", $f, "\n" }' | tail -1 
0
source

By default, the code below searches for a subtree under the current working directory. You can also specify a few more subtrees to search on the command line.

 #! /usr/bin/env perl use strict; use warnings; use File::Find; my($newest_mtime,$path); sub remember_newest { return if -l || !-f _; my $mtime = (stat _)[9]; ($newest_mtime,$path) = ($mtime,$File::Find::name) if !defined $newest_mtime || $mtime > $newest_mtime; } @ARGV = (".") unless @ARGV; for (@ARGV) { if (-d) { find \&remember_newest, @ARGV; } else { warn "$0: $_ is not a directory.\n"; } } if (defined $path) { print scalar(localtime $newest_mtime), "\t", $path, "\n"; } else { warn "$0: no files processed.\n"; exit 1; } 

As written, the code does not follow symbolic links. If you specify a symbolic link on the command line, you will see the output

  $ ./find-newest ~ / link-to-directory
 ./find-newest: no files processed. 

With bash, you need to add a trailing slash to force dereferencing.

  $ ./find-newest ~ / link-to-directory /
 Thu Jan 1 00:00:00 1970 hello-world 
0
source

Source: https://habr.com/ru/post/1413814/


All Articles