3

How to find the latest one modified file by "find" command in directory and subdir ? I need take only one file.

Oliver Salzburg
  • 89,072
  • 65
  • 269
  • 311
Aleksandr
  • 31
  • 1

2 Answers2

1

In Linux you can use

find . -type f -printf "%TY-%Tm-%Td %TT %p\n" | sort | tail -n 1

That'll list all files (-type f) and print those with timestamps, then sort and print only last one.

If you don't want to print timestamp too, you can use

find . -type f -printf "%TY-%Tm-%Td %TT %p\n" | sort | tail -n 1 | cut -d " " -f 3-
Olli
  • 7,739
0

Since sort crashes if the file list is too large, here is another solution:

ls -lRU --time-style=long-iso "$PWD"/* | awk 'BEGIN {\
    cont=0; newd=20000101; \
} { \
    gsub(/-/,"",$6); if (substr($0,0,1)=="/") \
    { \
        pat=substr($0,0,length($0)-1)"/"; $6="" \
    }; \
    if( $6 ~ /^[0-9]+$/) { \
        if ( $6 > newd ) { \
            newd=$6; \
            newf=$8; \
            for(i=9; i<=NF; i++) { \
                newf=newf $i; \
            } \
            newf=pat newf; \
        }; \
        count++; \
    } \
} END { \
    print "newest date: ", newd, "\nFile:", newf, "\nTotal compared: ", count \
}' 

Just paste into bash.

I took this code from @Dr-Beco's answer at How can I find the oldest file in a directory tree and modified the code to show the NEWEST file. For explanation follow the link.

If you want a one-liner, strip the \+newline and you get

ls -lRU --time-style=long-iso "$PWD"/* | awk 'BEGIN { cont=0; newd=20000101;} {gsub(/-/,"",$6); if (substr($0,0,1)=="/"){pat=substr($0,0,length($0)-1)"/"; $6=""};if( $6 ~ /^[0-9]+$/) {if ( $6 > newd ) {newd=$6;newf=$8;for(i=9; i<=NF; i++) {newf=newf $i;}newf=pat newf;};count++;}} END {print "newest date: ", newd, "\nFile:", newf, "\nTotal compared: ", count}' 

Haven't found a way to show FILE dates only, not DIRs. Tried

ls --classify |grep -v /$

which should simply strip all dirs from ls output. but this somehow broke the code.

JPT
  • 225