- Sort the files in the directory recursively based on last modified date
- 7 Answers 7
- NO SVN
- How to Sort Output of ‘ls’ Command By Last Modified Date and Time
- Linux Basic ls Commands
- Sort Files Based on Time and Date
- Как сортировать файлы по дате с помощью команды LS в Linux
- 1) Каталог файлов c последней измененной датой / временем
- 2) Список файлов с последней измененной датой / временем (последнее внизу)
- 3) Отображение в удобном формате
- 4) Найти файлы, измененные за последние 10 минут
- 5) Недавно измененные 10 файлов
- List files by last edited date
- 4 Answers 4
- Mac OS X
Sort the files in the directory recursively based on last modified date
Sort the files in the directory recursively based on last modified date I have modified a lot of files in my directory want to know what are those files by sorting them by the last modified date and in that I want some of the extensions to be excluded in the svn directory I have a lot of .svn files too which I don’t want to show in the sort
7 Answers 7
find -printf "%TY-%Tm-%Td %TT %p\n" | sort -n
will give you something like
2014-03-31 04:10:54.8596422640 ./foo
2014-04-01 01:02:11.9635521720 ./bar
find -not -path «svn» -not -name «*svn» -printf «%TY-%Tm-%Td %TT %p\n» | sort -n this is exactly what I needed thanks a lot @ n.st
If you want to flatten the directory structure (thus sorting by date over all files in all directories, ignoring what directory the files are in) the find -approach suggested by @yeti is the way to go. If you want to preserve directory structure, you might try
which sorts directory based.
In bash, run shopt -s globstar first. In ksh93, run set -o globstar first. In zsh, you’re already set.
This will return an error if you have so many files that the command line length limit on your system is exceeded. In zsh, you can use this instead:
This one will list all files in with topmost being oldest modified
find -type f -print0 | xargs -0 ls -ltr
And with this the latest modified is topmost
find -type f -print0 | xargs -0 ls -lt
Note that this only works if the list of file names doesn’t exceed the total command line length limit on your system.
@Gilles: You mean xargs -0 (in both cases). xargs -print0 is equivalent to xargs -p -r -i -n -t -0 or xargs -inprt0 or xargs -0ntrip , which is probably not what you meant.
Assuming you are usuig GNU find, try:
find $SOMEPATH -exec stat -c '%Y %n' '<>' + | sort -n
You could use find ‘s -printf option to avoid invoking a separate process (or several, depending on the number of files). See my answer for an example.
Knowing that there are other ways to do it, I wanted to give stat a chance and show -exec . + . Really! Sometimes I think, stat deserves more attention. and noone should take recipes from here without reading about the ingredients and thinking about consequences.
@yeti — If your find doesn’t have -printf , you can use -exec sh -c ‘printf. ‘ to get much of the same functionality. That would include access to $(pwd) for fully qualified paths as well.
I met lots of linux users never having read about stat . So sometimes I just want to direct some attention on stat . I think stat deserves it.
To robustly list the filenames only using recent GNU tools:
find . -printf '%A@ %p\0' | sort -nz | sed -z 's/^[^ ]* //' | tr '\0' '\n'
find $DIR -depth -maxdepth 3 \ -type d -readable -printf \ 'printf "\\n%p\\n" ls -t --color=always "%p"\n' |\ . /dev/stdin 2>&-
This avoids any argument list problems because the only argument ls will ever receive is the name of the directory you want listed. You can do this with anything you like.
The shell just . sources the |pipe as a shell script — it’s the same process and doesn’t have the issues you can encounter when execve is called.
In any case — the above only goes three-deep which is adjustable by changing maxdepth . It also deep first — so you work your way backwards to your current directory from depth .
You might notice you also get $LSCOLORS — on my machine it also provides neatly printed columns and everything else you would want from ls — or, for that matter, anything you can imagine you’d wanna do with . source.
NO SVN
Again, this’ll do anything you expect of ls . So hiding .svn files is as simple as changing the ls line to:
ls -t --color=always --hide="*svn" "%p"\n
Or if you want to see svn extensions in every folder BUT ./svn you could change it so the whole command looks like this:
find $DIR -depth -maxdepth 3 \ -type d -readable -printf \ 'printf "\\n%p\\n" ; hide= [ "%p" = "./svn" ] && hide="*svn" ls -t --color=always --hide="$hide" "%p"\n' |\ . /dev/stdin 2>&-
Personally, I like it with ls’s -s and, if you care, -u will sort by access time rather than mod time.
How to Sort Output of ‘ls’ Command By Last Modified Date and Time
One of the commonest things a Linux user will always do on the command line is listing the contents of a directory. As we may already know, ls and dir are the two commands available on Linux for listing directory content, with the former being more popular and in most cases, preferred by users.
When listing directory contents, the results can be sorted based on several criteria such as alphabetical order of filenames, modification time, access time, version and file size. Sorting using each of these file properties can be enabled by using a specific flag.
In this brief ls command guide, we will look at how to sort the output of ls command by last modification time (date and time).
Let us start by executing some basic ls commands.
Linux Basic ls Commands
1. Running ls command without appending any argument will list current working directory contents.
2. To list contents of any directory, for example /etc directory use:
3. A directory always contains a few hidden files (at least two), therefore, to show all files in a directory, use the -a or —all flag:
4. You can as well print detailed information about each file in the ls output, such as the file permissions, number of links, owner’s name and group owner, file size, time of last modification and the file/directory name.
This is activated by the -l option, which means a long listing format as in the next screenshot:
Sort Files Based on Time and Date
5. To list files in a directory and sort them last modified date and time, make use of the -t option as in the command below:
6. If you want a reverse sorting files based on date and time, you can use the -r option to work like so:
We will end here for now, however, there is more usage information and options in the ls command, so make it a point to look through it or any other guides offering ls command tricks every Linux user should know or use sort command. Last but not least, you can reach us via the feedback section below.
Как сортировать файлы по дате с помощью команды LS в Linux
Команда ls используется для отображения содержимого каталога, и результаты могут быть отсортированы по нескольким критериям, например по дате, алфавитному порядку имен файлов, времени модификации, времени доступа, версии и размера файла.
В этой статье я покажу вам, как сортировать файлы по дате с помощью команды ls в Linux.
1) Каталог файлов c последней измененной датой / временем
Чтобы просмотреть файлы и отобразить последние измененные файлы сверху, мы будем использовать опции -lt с командой ls.
output total 24 -rw-rw-r--. 1 root utmp 2304 Sep 8 14:58 utmp -rw-r--r--. 1 root root 4 Sep 8 12:41 dhclient-eth0.pid drwxr-xr-x. 4 root root 100 Sep 8 03:31 lock drwxr-xr-x. 3 root root 60 Sep 7 23:11 user drwxr-xr-x. 7 root root 160 Aug 26 14:59 udev drwxr-xr-x. 2 root root 60 Aug 21 13:18 tuned
2) Список файлов с последней измененной датой / временем (последнее внизу)
Мы будем использовать опции -ltr с командой ls для отображения файлов определенного каталога с недавно измененными файлами внизу.
$ ls -ltr /run total 13404 drwxr-xr-x 2 root root 4096 Dec 14 2016 scripts -rwxr-xr-x 1 root root 4688 Dec 14 2016 perms.py -rw-r--r-- 1 root root 9718 Jun 23 14:47 ddagent-install.log -rw-r--r-- 1 root root 1457471 Jun 26 01:26 rocket.zip drwxr-xr-x 2 root root 4096 Jun 26 10:40 ssl-21APR2018-11JUN2020 drwxr-xr-x 6 root root 4096 Jun 27 09:29 incubator-pagespeed-ngx-latest-stable drwxr-xr-x 9 root root 4096 Jun 27 09:29 nginx-1.15.0 drwxr-xr-x 3 root root 4096 Jul 2 19:55 rocket-nginx -rw-r--r-- 1 root root 18186 Jul 11 13:17 memcachy.zip -rwxr-xr-x 1 root root 12202195 Sep 4 12:21 Linux_64bit.install :~#
Если вы хотите отсортировать по каталогу, по датам используйте
3) Отображение в удобном формате
Мы будем использовать опции -halt с помощью команды ls для отображения файлов определенного каталога в форматах для чтения
Он использует суффиксы K, M, G и T (или без суффикса для байтов)
total 28K -rw-rw-r--. 1 root utmp 1.9K Oct 28 06:02 utmp drwxr-xr-x. 3 root root 60 Oct 28 06:02 user drwxr-xr-x. 4 root root 100 Oct 28 03:48 lock -rw-r--r--. 1 root root 4 Oct 28 02:50 dhclient-eth0.pid drwxr-xr-x. 7 root root 160 Oct 25 12:16 udev drwxr-xr-x. 21 root root 600 Oct 25 12:15 .
4) Найти файлы, измененные за последние 10 минут
Мы можем получить файлы, измененные за последние 10 минут командой ниже:
$ find . -mmin -10 -type f -exec ls -l <> +
-rw-r--r--. 1 root root 53 Nov 1 01:58 ./smart.txt -rw-r--r--. 1 root root 15 Nov 1 02:00 ./test/file1
5) Недавно измененные 10 файлов
Посмотрите, как проверить недавно измененные 10 файлов в каталоге с помощью команд ls.
Мы будем использовать комбинацию команд «ls» и «head».
Ниже команда покажет измененные 10 файлов с недавно обновленным файлом вверху
-rw-rw-r--. 1 root utmp 1920 Oct 31 01:57 utmp drwxr-xr-x. 3 root root 60 Oct 31 01:57 user drwxr-xr-x. 16 root root 400 Oct 30 23:06 systemd -rw-r--r--. 1 root root 4 Oct 30 18:42 dhclient-eth0.pid drwxr-xr-x. 4 root root 100 Oct 30 03:06 lock drwxr-xr-x. 7 root root 160 Oct 28 06:09 udev -rw-------. 1 root root 3 Oct 25 12:15 syslogd.pid drwxr-xr-x. 2 root root 60 Oct 25 12:15 tuned -rw-r--r--. 1 root root 4 Oct 25 12:15 sshd.pid
с комбинацией tail, он показывает недавно обновленный файл внизу.
drwxr-xr-x. 3 root root 100 Oct 25 12:15 NetworkManager -rw-r--r--. 1 root root 4 Oct 25 12:15 sshd.pid drwxr-xr-x. 2 root root 60 Oct 25 12:15 tuned -rw-------. 1 root root 3 Oct 25 12:15 syslogd.pid drwxr-xr-x. 7 root root 160 Oct 28 06:09 udev drwxr-xr-x. 4 root root 100 Oct 30 03:06 lock -rw-r--r--. 1 root root 4 Oct 30 18:42 dhclient-eth0.pid drwxr-xr-x. 16 root root 400 Oct 30 23:06 systemd drwxr-xr-x. 3 root root 60 Oct 31 01:57 user -rw-rw-r--. 1 root utmp 1920 Oct 31 01:57 utmp
Спасибо, что прочитали эту статью и, пожалуйста, прокомментируйте ниже, если вы найдете какие-либо другие варианты полезными.
List files by last edited date
I have a directory: /home/user/ How can I list every file in this directory (including those in sub directories) and order them by the date that they were last modified?
4 Answers 4
where -R means recursive (include subdirectories) and -t means «sort by last modification date».
To see a list of files sorted by date modified, use:
An alias can also be created to achieve this:
Where -h gives a more readable output.
Thanks, that’s perfect. I added a -l in there too so I can actually see the dates so for anyone who searches this out later, it’s- $ ls -lRt
If you’re doing this at the prompt and want to see the most recently modified files, consider ls -lrt[RhA] . the -r reverses the sort order, leaving recently edited stuff at the bottom of the list.
I have expanded on this answer because using ll -Rt was the perfect solution for me as I needed to see the files by date most recently modified. This might be helpful to others.
@MusTheDataGuy ll is does not exists and is not a command. It is mostly an alias in the bash shell, but not defined in most/some/? linux distributions. Some define it as an alias ll=’ls -l’ in /etc/bash.bashrc or /etc/.bashrc. Thus it may not work and it may not exists on OPs system. Use ls -l -Rt at least, as ls is a standard command as defined by posix. Or specify you meant alias ll=’ls -l’; ll -Rt .
If you’d like a master list in which all the files are sorted together by modification date, showing the directory they’re in, but not grouped by directory, you can use this:
find . -type f -printf "%-.22T+ %M %n %-8u %-8g %8s %Tx %.8TX %p\n" | sort | cut -f 2- -d ' '
The result looks a lot like ls -l :
-rw-r--r-- 1 root root 3892 08/11/2009 11:03:36 /usr/share/man/man1/xmllint.1.gz -rw-r--r-- 1 root root 22946 08/13/2009 11:59:20 /usr/share/man/man1/curl.1.gz -rw-r--r-- 1 root root 728 08/17/2009 12:06:33 /usr/share/man/man1/thunderbird.1.gz -rw-r--r-- 1 root root 873 08/18/2009 10:52:47 /usr/share/man/man1/libgnutls-config.1.gz -rw-r--r-- 1 root root 2552 08/19/2009 02:00:34 /usr/share/man/man3/Purple.3pm.gz -rw-r--r-- 1 root root 9546 08/19/2009 02:02:00 /usr/share/man/man1/pidgin.1.gz -rw-r--r-- 1 root root 2201 08/19/2009 02:02:46 /usr/share/man/man3/Pidgin.3pm.gz -rw-r--r-- 1 root root 926 08/19/2009 02:03:05 /usr/share/man/man1/purple-remote.1.gz -rw-r--r-- 1 root root 18052 08/19/2009 04:11:47 /usr/share/man/man1/mono.1.gz -rw-r--r-- 1 root root 1845 08/19/2009 04:11:47 /usr/share/man/man5/mono-config.5.gz
Mac OS X
For those of you using Mac OS X, option -printf is not available on BSD find (you will get this error: find: -printf: unknown primary or operator ). Fortunately you can Install GNU find through Homebrew (there should be an option to Fink and Macports as well):
After install it the GNU find should be available to you as gfind . So, all you need to do is change the line above to:
gfind . -type f -printf "%-.22T+ %M %n %-8u %-8g %8s %Tx %.8TX %p\n" | sort | cut -f 2- -d ' '