Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find files bigger then some size, and sort them by last modification date?

Tags:

find

bash

I need to write script which write down each files in selected catalog, which are bigger then some size. Also I need to sort them by size, name and last modification date.

So I have made the first two cases:

Sort by size

RESULTS=`find $CATALOG -size +$SIZE | sort -n -r | sed 's_.*/__'`

Sort by name

RESULTS=`find $CATALOG -size +$SIZE | sed 's_.*/__' | sort -n `

But I have no idea how to sort results by last modification date.

Any help would be appreciated.

like image 709
Mateusz Rogulski Avatar asked Dec 15 '12 11:12

Mateusz Rogulski


1 Answers

One of the best approaches, provided you don't have too many files, is to use ls to do the sorting itself.

Sort by name and print one file per line:

find $CATALOG -size +$SIZE -exec ls -1 {} +

Sort by size and print one file per line:

find $CATALOG -size +$SIZE -exec ls -S1 {} +

Sort by modification time and print one file per line:

find $CATALOG -size +$SIZE -exec ls -t1 {} +

You can also play with the ls switches: Sort by modification time (small first) with long listing format, with human-readable sizes:

find $CATALOG -size +$SIZE -exec ls -hlrt {} +

Oh, you might want to only find the files (and ignore the directories):

find $CATALOG -size +$SIZE -type f -exec ls -hlrt {} +

Finally, some remarks: Avoid capitalized variable names in bash (it's considered bad practice) and avoid back ticks, use $(...) instead. E.g.,

results=$(find "$catalog" -size +$size -type f -exec ls -1rt {} +)

Also, you probably don't want to put all the results in a string like the previous line. You probably want to put the results in an array. In that case, use mapfile like this:

mapfile -t results < <(find "$catalog" -size +$size -type f -exec ls -1rt {} +)
like image 151
gniourf_gniourf Avatar answered Nov 08 '22 12:11

gniourf_gniourf