27

I want to sort only files by update dates including sub-directories.

I found out ls -lrtR | grep ^-. but it doesn't seem to sort by update dates.

And I need to save this list into a file. Is it possible?

Apr 01 2010  InsideDoosanServiceImpl.class  // in A directory
Apr 08 2010  MainController.class  // in B directory
Apr 07 2010  RecommendController.class  // in B directory
Apr 01 2010  MainDao.class  // in B directory

I mean the whole list is not ordered by date, but first ordered by folder, and ordered by date.

I want a list first ordered by date including all sub-directories.

Anthon
  • 79,293
Deckard
  • 391

2 Answers2

24

With ls, -R will recurse directories and -t will sort by modification. However, it traverses directories recursively and applies -t to each directory. It doesn't accumulate all files from all directories and then sort. (As far as I understand, the latter is what you want)

With gnu find(1) you can specify the format of output to include the number of seconds since epoch and the filename, then you can pipe this to sort(1).

find . -type f -printf "%T@ %f\n" | sort -n > out.txt
  • Yea GNU find does help. But OP works on AIX machines so GNU find wasn't available to him. – jaypal singh Jan 18 '12 at 07:52
  • It's too bad ls can't be made to accumulate files before sorting. ls is so fast compared to find. – Nathan Arthur Jan 27 '16 at 21:53
  • ls and find reads the same data, so I can't imagine any reason ls should be considerably faster than find. On my system find is 5 times faster (searching through roughly half a million files) – Rolf Rander Jan 27 '16 at 22:01
  • 11
    You might want a full date/time and not only the file name but also the path in the output, in that case, modify the formatting string: find . -type f -printf "%T@ %Tc %p\n" | sort -n > out.txt yielding output entries like 1427913836.2330520210 wed 1 apr 2015 20:43:56 ./subdir/file.txt. – Carl Feb 03 '16 at 23:08
  • Great. That really helped me out. I've been looking for a way to sort into subdirectories for ages! – bhu Boue vidya Apr 09 '18 at 01:14
22

I am not sure what exactly do you mean by update dates, but you are using -r option which according to man does this -

-r Reverse the order of the sort to get reverse lexicographical order or the oldest entries first (or largest files last, if combined with sort by size

I think this should be good enough for you if you need files sorted by time.

ls -lRt

If you don't need all the other stuff listed by ls then you can use -

ls -1Rt

To capture the result in a file, you can use the redirection operator > and give a file name. So you can do something like this -

ls -lRt > sortedfile.list

Update:

find . -type f -exec ls -lt {} +

This will sort files so that the newest files are listed first. To reverse the sort order, showing newest files at the end, use the following command:

find . -type f -exec ls -lrt {} +
jaypal singh
  • 1,592