Linux sort file by date

How can I sort the output of ‘ls’ by last modified date?

The ls man page describes this in more details, and lists other options.

In case anyone’s wondering, both the -t and -r arguments are specified in the section about ls in the POSIX standard, so should be compatible across Unices.

@EvgeniSergeev DONT MEMORISE ls -halt a simple mistype may cause your server to crash! linux.die.net/man/8/halt

Try this: ls -ltr . It will give you the recent to the end of the list

I used this to get the list of files in my Git repository by their last edit date. ls -alt $(git ls-files -m) Thanks!

For a complete answer here is what I use: ls -lrth

Put this in your startup script /etc/bashrc and assign an alias like this: alias l=’ls -lrth’ Restart your terminal and you should be able to type l and see a long list of files.

You can also add it in ~/.bash_aliases just for your user (one can create the file if it doesn’t exist already

I use sometime this:

find . -type f -mmin -5 -print0 | xargs -0 /bin/ls -tr 
find . -type f -mmin -5 -print0 | xargs -0 /bin/ls -ltr 

to look recursively for which files were modified in last 5 minutes.

. or now, with recent version of GNU find:

find . -type f -mmin -5 -exec ls -ltr <> + 

. and even for not limiting to files:

find . -mmin -5 -exec ls -ltrd <> + 

(note the -d switch to ls for not displaying content of directories)

More robust way?

By recursively you mean it lists all files in subdirectories, doesn’t ls already have a switch to do that?

@jiggunjer ls -Rltr will sort by dir, then by dates, find -type f -mmin -5 -exec ls -ltr <> + will just print files modified in last 5 minutes, sorted by date, regardless of directory tree!

Note that this won’t work if the list of files is too long to be passed as one shell invocation to ls (unix.stackexchange.com/a/118200/27186) – then you’ll see one sorted bunch of files, then another sorted bunch of files, etc. but the whole list won’t be sorted. See superuser.com/questions/294161/… for sorting longer lists with find.

Mnemonic

For don’t ignore entries starting with . and sort by date (newest first):

For don’t ignore entries starting with . and reverse sort by date (oldest first):

Читайте также:  Linux git clone repository

For don’t ignore entries starting with . , use a long listing format and sort by date (newest first):

For print human readable sizes, don’t ignore entries starting with . , use a long listing format and sort by date (newest first) (@EvgeniSergeev note):

but be careful with the last one, because a simple mistype can cause a server crash. (@Isaac note)

Источник

Как сортировать файлы по дате с помощью команды 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.

Читайте также:  Сгенерировать хеш пароля linux

Мы будем использовать комбинацию команд «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):

Читайте также:  What are some linux operating systems

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 ' ' 

Источник

How do I do a ls and then sort the results by date created?

In what order are the dated ordered by? Certainly not alphanumeric order. ls -lt sorts by modification time. But I need creation time.

There does seem to be a way to get the file creation time in Linux if the file is on a ext4 file system. See: unix.stackexchange.com/a/131347/182996

7 Answers 7

Most unices do not have a concept of file creation time. You can’t make ls print it because the information is not recorded. If you need creation time, use a version control system: define creation time as the check-in time.

If your unix variant has a creation time, look at its documentation. For example, on Mac OS X (the only example I know of), use ls -tU . Windows also stores a creation time, but it’s not always exposed to ports of unix utilities, for example Cygwin ls doesn’t have an option to show it. The stat utility can show the creation time, called “birth time” in GNU utilities, so under Cygwin you can show files sorted by birth time with stat -c ‘%W %n’ * | sort -k1n .

Note that the ctime ( ls -lc ) is not the file creation time, it’s the inode change time. The inode change time is updated whenever anything about the file changes (contents or metadata) except that the ctime isn’t updated when the file is merely read (even if the atime is updated). In particular, the ctime is always more recent than the mtime (file content modification time) unless the mtime has been explicitly set to a date in the future.

Источник

Оцените статью
Adblock
detector