1

I'm trying to use find and ls to sort files based on date, however, it's not doing anything. Here's my command:

find ./.BUBackups -name "test*" -exec ls -t {} \;

I also tried:

find ./.BUBackups -name "test*" -exec ls -lt {} \;

In testing, -t is simply doing -nothing-. -l works, but if I input -t it acts as if I didn't put it in at all. However, ls -t or ls -lt works perfectly fine when I'm not running it through exec, in others words simply typing ls -t works

Is this a glitch? or am I doing something wrong?

0

2 Answers 2

3

The -exec argument to find executes the specified command once for each file that find locates. So if you have files test_a, test_b, and test_c, your command will be equivalent to:

ls -lt test_a
ls -lt test_b
ls -lt test_c

In other words, each listing is performed independently per file, so the files will be listed in whatever order find locates them, rather than in order of modification time, like the -t option to ls specifies.

What you really want is something like find ./.BUBackups -name 'test*' | xargs ls -lt, which, with the example files I used above, would be equivalent to ls -lt test_a test_b test_c. Since you're now using one invocation of ls to list all of the files you're interested in, it can put them in the proper mtime order.

1
  • This is exactly what I needed! Thanks (to both of you)
    – Wipqozn
    Commented Feb 11, 2011 at 18:56
3

The reason -t isn't working is that find is executing ls once for each found file separately so the output is in the order the files are found. To make it work the way you expect:

find ./.BUBackups -name "test*" -exec ls -lt {} +

or

find ./.BUBackups -name "test*" -print0 | xargs -0 -exec ls -lt 
3
  • Does ls is guaranteed to be called just one time? Otherwise I guess you'll get multiple lists of sorted files.
    – cYrus
    Commented Feb 11, 2011 at 18:28
  • 1
    @cYrus: No, not guaranteed. It will be limited to the maximum argument length supported by your system. If you're using ls -lt with that many files, you should probably be using a different approach altogether. Commented Feb 11, 2011 at 18:36
  • This is exactly what I needed! Thanks (to both of you)
    – Wipqozn
    Commented Feb 11, 2011 at 18:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .