Сортировка файлов по дате изменения linux

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.

Читайте также:  Remove all files in linux command

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):

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.

Читайте также:  Remote file system in 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

Спасибо, что прочитали эту статью и, пожалуйста, прокомментируйте ниже, если вы найдете какие-либо другие варианты полезными.

Источник

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.

Читайте также:  Will steam games run on linux

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.

Источник

sort list of files by date in bash

How can I sort this list of files by some criteria — like their last accessed time, or last changed time? Thanks in advance.

3 Answers 3

You can use stat command with sort like this:

while read -r line; do stat -c '%Y %n' "$line" done < file_list.txt | sort -n | cut -d ' ' -f2 
  • stat -c '%Y %n' lists time of last modification, seconds since Epoch followed by a space and file name
  • sort -n sorts timestamps and their filename numerically
  • cut -d ' ' -f2 prints only file names from sort's output

Try one liner (by modification time):

This will fail if any file contains spaces. Also, this is subject to pathname expansion. To be “safe”: (set -f; IFS=$'\n'; ls -t $(cat file_list.txt)) .

You can get the most recently changed file with

cat file_list.txt | xargs stat -c '%Y %n' | sort | tail -1 | cut -c 12- 

You can get the most recent timestamp with

cat file_list.txt | xargs stat -c '%Y %n' | sort | tail -1 | cut -c -10 

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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