Sami
Sami

Reputation: 492

Listing most recent files whose total sizes are about a certain value

I would like to copy the most recent files in a directory to another directory such that the total sizes of the files I would like to copy should be 10gb, let say.

I know that I can list the most recent 10 files with a certain amount of size like this:

find . -maxdepth 1 -type f -size +100M -print0 | xargs -0 ls -Shal | head

But, is there any way to find the most recent files whose total sizes are about 10gb?

Thanks

Upvotes: 0

Views: 38

Answers (1)

Michael Vehrs
Michael Vehrs

Reputation: 3363

Yes, that is possible. find has a printf action that allows you to output only the information you are interested in. In your case, that would be a timestamp (e.g. last modification time), the file size, and the name of the file. You can then sort the output according to the timestamp, and use awk to sum the file sizes and output the file names up to a certain limit:

find "$some_directory" -printf "%T@ %s %p\n" | sort -nr \
    | awk '{ a = a + $2; if (a > 10000) { print a; exit; }; print $3; }'

Adjust the limit according to your needs, and remove print a if you are not interested in the result. If you want to include the file that pushes the sum over the limit, replace print a with print $3.

Upvotes: 1

Related Questions