Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Using the Mac OS X Terminal, how do I write a find command that orders results by modification date (most recent first)?

There are similar questions already, but they refer to GNU find and POSIX, but I do not know whether Mac OS X is GNU or POSIX or something else.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

OS X is fully POSIX compliant.

Something like that should do:

find . -type f -name "*.txt" -print0 | xargs -0 ls -tl

Some notes:

  • The -t option in ls will sort by mtime.
  • xargs is used to pass the filenames as an argument to ls. Note that you have to use -print0 in find and -0 in xargs if you have files with spaces in their names. Also, the maximum amount of arguments is limited by the ARG_MAX variable. To find out how many these are, enter getconf ARG_MAX.
  • You can supply -r to reverse the sort order (→ oldest files first)
  • The other find and ls options are – as usual – outlined in the manuals (man find or man ls).
share|improve this answer
    
ls -ltr to reverse the order. –  Daniel Beck Jun 18 '11 at 9:19
    
Xe'll only get them sorted within groups of (slightly less than) ARG_MAX filename characters that way, of course. –  JdeBP Jun 18 '11 at 10:59
    
Yup, thanks for the addition @JdeBP and Daniel. getconf ARG_MAX will show that number. –  slhck Jun 18 '11 at 11:20
    
ah my problem now is that I am using this command in a applescript, and was using the result to read the contents of that file. But now the result contains date information, not just the filename: do shell script "find /Users/akw/Library/Preferences/ByHost/ -name 'com.apple.windowserver*' -print0 | xargs -0 ls -tl | head -1" returns this --> "-rw-------@ 1 akw staff 5512 Jun 19 07:52 /Users/akw/Library/Preferences/ByHost//com.apple.windowserver.1FC3A841-2C0C-5F48‌​-B746-1DEE064F6D12.plist" –  zadam Jun 18 '11 at 21:56
    
@zadam then use ls -t instead of ls -tl. The -l gives you a long listing including the dates. I didn't know what you were trying to do exactly, so sorry for that - I assumed you would like to see the mtime as well. –  slhck Jun 18 '11 at 22:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.