Linux посмотреть последние измененные файлы

How to recursively find and list the latest modified files in a directory with subdirectories and times

I have several directories with several subdirectories and files in them. I need to make a list of all these directories that is constructed in a way such that every first-level directory is listed next to the date and time of the latest created/modified file within it.

To clarify, if I touch a file or modify its contents a few subdirectory levels down, that timestamp should be displayed next to the first-level directory name. Say I have a directory structured like this:

and I modify the contents of the file example.txt , I need that time displayed next to the first-level directory alfa in human readable form, not epoch. I’ve tried some things using find, xargs , sort and the like, but I can’t get around the problem that the filesystem timestamp of ‘alfa’ doesn’t change when I create/modify files a few levels down.

@user3392225 A fork of github / shadkam / recentmost can be found at github.com/ConradHughes/recentmost with the -0 option to use with find ‘s -print0

22 Answers 22

#!/bin/bash find $1 -type f -exec stat --format '%Y :%y %n' "<>" \; | sort -nr | cut -d: -f2- | head 

Execute it with the path to the directory where it should start scanning recursively (it supports filenames with spaces).

If there are lots of files it may take a while before it returns anything. Performance can be improved if we use xargs instead:

#!/bin/bash find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head 

Your «fast method» should also be able to use print0 to support spaces and even linefeeds in filenames. Here’s what I use: find $1 -type f -print0 | xargs -0 stat —format ‘%Y :%y %n’ | sort -nr | cut -d: -f2- | head This still manages to be fast for me.

Some directories I was looking in didn’t allow me to stat them, so I made the following changes (to the ‘fast’ one) so I didn’t have to see the errors in my final output. find $ <1>-type f | xargs stat —format ‘%Y :%y %n’ 2>/dev/null | sort -nr | cut -d: -f2-

On Mac OS X it’s not GNU’s stat so command fails. You have to brew install coreutils and use gstat instead of stat

You don’t need to run stat since find PATH -type f -printf «%T@ %p\n»| sort -nr does the job. It’s also a bit faster that way.

On Mac OS X, without installing gstat or anything else, you can do: find PATH -type f -exec stat -f «%m %N» «<>» \; | sort -nr | head

To find all files whose file status was last changed N minutes ago:

Use -ctime instead of -cmin for days:

On FreeBSD and MacOS: You can also use -ctime n[smhdw] for seconds, minutes, hours, days, and weeks. Days is the default if no unit is provided.

# FreeBSD and MacOS only: find . -ctime -30s find . -ctime -15 find . -ctime -52w 

great idea. Consider doing stat . on directory first to get an idea of modification dates you should be looking at

Читайте также:  Broadcast messages in linux

GNU find (see man find ) has a -printf parameter for displaying the files in Epoch mtime and relative path name.

redhat> find . -type f -printf '%T@ %P\n' | sort -n | awk '' 

Thanks! This is the only answer that is fast enough to search through my very wide directory structure in a reasonable time. I pass the output through tail to prevent thousands of lines from being printed in the output.

Another comment: the awk ‘‘ part seems to cause issues when there are filenames with spaces. Here is a solution using sed instead, and it also prints the time in addition to the path: find . -type f -printf ‘%T@ %Tc %P\n’ | sort -n | tail | sed -r ‘s/^.//’

The -printf variant is far quicker than calling a ‘stat’ process each time — it cut hours off my backup job(s). Thanks for making me aware of this. I avoided the awk/sed thing as I’m only concerned about the last update within the tree — so X=$(find /path -type f -printf ‘%T %p\n’ | grep -v something-I-don-tcare-about | sort -nr | head -n 1) and a echo $ worked well for me (give me stuff up to the first space)

All will not works if filename across multiple line. Use touch «lalab» to create such file. I think unix utilities design has big flaw about filename.

stat --printf="%y %n\n" $(ls -tr $(find * -type f)) 

If there are spaces in filenames, you can use this modification:

OFS="$IFS";IFS=$'\n';stat --printf="%y %n\n" $(ls -tr $(find . -type f));IFS="$OFS"; 

This will not work if you have a very large number of files. the answers that use xargs solve that limit.

@carlverbiest indeed a large number of files will break slashdottir’s solution. Even xargs-based solutions will be slow then. user2570243’s solution is best for big filesystems.

IFS=$’\n’ isn’t safe in any event when handling filenames: Newlines are valid characters in filenames on UNIX. Only the NUL character is guaranteed not to be present in a path.

#!/bin/bash stat --format %y $(ls -t $(find alfa/ -type f) | head -n 1) 

It uses find to gather all files from the directory, ls to list them sorted by modification date, head for selecting the first file and finally stat to show the time in a nice format.

At this time it is not safe for files with whitespace or other special characters in their names. Write a commend if it doesn’t meet your needs yet.

halo: I like your answer, it works well and prints out the correct file. I doesn’t help me however since there are too many sublevels in my case. So I get «Argument list too long» for ls. and xargs wouldn’t help in this case either. I’ll try something else.

Читайте также:  Virtualbox linux всем пользователям

I solved this using PHP instead. A recursive function that descends through the filesystem tree and stores the time of the most recently modified file.

On MacOS I needed to use stat $(ls -t $(find alfa/ -type f) | head -n 10) . —format would be -f , but there is no %y and I didn’t bother finding a replacement.

Ignoring hidden files — with nice & fast time stamp

Here is how to find and list the latest modified files in a directory with subdirectories. Hidden files are ignored on purpose. Whereas spaces in filenames are handled well — not that you should use those! The time format can be customised.

$ find . -type f -not -path '*/\.*' -printf '%TY.%Tm.%Td %THh%TM %Ta %p\n' |sort -nr |head -n 10 2017.01.25 18h23 Wed ./indenting/Shifting blocks visually.mht 2016.12.11 12h33 Sun ./tabs/Converting tabs to spaces.mht 2016.12.02 01h46 Fri ./advocacy/2016.Vim or Emacs - Which text editor do you prefer?.mht 2016.11.09 17h05 Wed ./Word count - Vim Tips Wiki.mht 

More find galore can be found by following the link.

This command works on Mac OS X:

find «$1» -type f -print0 | xargs -0 gstat —format ‘%Y :%y %n’ | sort -nr | cut -d: -f2- | head

On Linux, as the original poster asked, use stat instead of gstat .

This answer is, of course, user37078’s outstanding solution, promoted from comment to full answer. I mixed in CharlesB’s insight to use gstat on Mac OS X. I got coreutils from MacPorts rather than Homebrew, by the way.

And here’s how I packaged this into a simple command ~/bin/ls-recent.sh for reuse:

#!/bin/bash # ls-recent: list files in a directory tree, most recently modified first # # Usage: ls-recent path [-10 | more] # # Where "path" is a path to target directory, "-10" is any argument to pass # to "head" to limit the number of entries, and "more" is a special argument # in place of "-10" which calls the pager "more" instead of "head". if [ "more" = "$2" ]; then H=more; N='' else H=head; N=$2 fi find "$1" -type f -print0 |xargs -0 gstat --format '%Y :%y %n' \ |sort -nr |cut -d: -f2- |$H $N 

Источник

Поиск последних измененных файлов/папок в Unix/Linux

Иногда, нужно найти все измененные файлы или папки в Unix/Linux ОС и в моей статье «Поиск последних измененных файлов/папок в Unix/Linux» я расскажу как это сделать.

Чтобы найти все файлы, которые были изменены с момента определенного времени (т.е. час назад, день назад, 24 часа назад и так далее) в Unix и Linux имеется команда find и она очень пригодиться для таких целей.
Чтобы найти все файлы, которые были изменены в течение последних 24 часов (последний полный день) в текущем каталоге и в его подкаталогах, используйте:

Опция «-mtime -1» сообщает команде find искать модифицированные файлы за последние сутки (24 часа).
Опция «-print» сообщает «find» выводить файлы и их пути (где они лежат) и данную команду можно заменить на «-ls» если нужно вывести подробную информацию о файле.

Например нужно найти файлы, что были изменены за последние 30 минут в папке /home/captain:

# find /home/captain -type f -mmin -30

И приведу пример подобного, но для папки:

# find /home/captain -type d -mmin -30

Например нужно найти измененные файлы за 5 дней, но не включать в поиск вчерашний день (за последний день):

# find /home/captain -type f -mtime -5 ! -mtime -1

Для полного счастья, можно вывести время модификации и отсортировать по нему:

# find /home/captain -type f -mtime -5 ! -mtime -1 -printf '%TY-%Tm-%Td %TT %p\n' | sort -r

Чтобы ограничить уровень вложенности, добавьте параметр «-depth». Например, поиск с уровнем вложенности не более 3 папок:

# find /home/captain -type f -mmin -30 -depth -3

Поиск файлов в /home/captain директории (и во всех ее подпапках) которые были изменены в течение последних 60 минут, и вывести их атрибуты:

$ find/ home/captain -type f -mmin -60 -exec ls -al <> \;

В качестве альтернативы, вы можете использовать xargs команду, чтобы достичь того же:

$ find /home/captain -type f -mmin -60 | xargs ls -l

Поиск последних измененных файлов/папок в Unix/Linux завершен.

Читайте также:  Linux zip all files in dir

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Рубрики

  • Arch Linux (167)
  • Commands (36)
  • Debian’s (635)
    • Administration tools Ubuntu (37)
    • Backups Debian’s (7)
    • Database в Ubuntu (58)
    • Games (игры) (1)
    • Monitoring в Debian и Ubuntu (49)
    • Virtualization в Ubuntu / Debian/ Linux Mint (41)
      • Docker (22)
      • Kubernetes (6)
      • KVM (4)
      • OpenVZ (3)
      • Vagrant (5)
      • VirtualBox (6)
      • ArgoCD (1)
      • Concourse (1)
      • Gitlab (1)
      • Jenkinks (4)
      • Spinnaker (1)
      • Apache (32)
      • Cherokee (1)
      • FTP-services (5)
      • Lighttpd (1)
      • Nginx (26)
      • PHP (27)
      • Proxy для Debian’s (2)
      • Tomcat (4)
      • Панели управления в Ubuntu/Debian/Mint (24)
      • Установка и настройка почты на Ubuntu/Debian (12)
      • Хранилища (clouds) (2)
      • Administration tools freeBSD (19)
      • Database во FreeBSD (52)
      • Monitoring во freeBSD (37)
      • Virtualization во FreeBSD (22)
      • VoIP (1)
      • Установка Web сервисов (91)
      • Установка и настройка почты (6)
      • Установка из ports (пакетов) (19)
      • Установка из sorce code (исходников) (23)
      • Непрерывная интеграция (CI) (27)
      • Database в MacOS (36)
      • Monitoring в Mac OS (31)
      • Security (безопасность) (12)
      • Virtualization в Mac OS (30)
        • Docker (19)
        • Kubernetes (6)
        • Vagrant (5)
        • VirtualBox (5)
        • ArgoCD (1)
        • CircleCI (1)
        • Concourse (1)
        • Gitlab (1)
        • Jenkinks (4)
        • Spinnaker (1)
        • Administration tools CentOS (49)
        • Backups RPM’s (4)
        • Database в CentOS (68)
        • Monitoring в CentOS (67)
        • Virtualization в CentOS/ Red Hat/ Fedora (42)
          • Docker (23)
          • Kubernetes (6)
          • KVM (5)
          • OpenVZ (2)
          • Vagrant (5)
          • VirtualBox (6)
          • VMWare (3)
          • ArgoCD (1)
          • Concourse (1)
          • Gitlab (1)
          • Jenkinks (4)
          • Spinnaker (1)
          • Apache (35)
          • Cherokee (1)
          • DNS (3)
          • FTP (10)
          • Nginx (33)
          • PHP (34)
          • Proxy для RedHat’s (2)
          • Tomcat (2)
          • Voice (2)
          • Панели управления в CentOS/Red Hat/Fedora (27)
          • Прокси сервер на CentOS/RHEL/Fedora (4)
          • Установка и настройка почты на CentOS/RHEL/Fedora (14)
          • Хранилища (clouds) (1)

          соц сети

          Unix-Linux- в примерах

          Unix-Linux- в примерах

          Unix-Linux- в примерах

          Архив новостей

          Свежие записи

          Свежие комментарии

          • Глеб к записи Установка Adobe Flash Player в Debian/Ubuntu/Mint
          • Максим к записи Заблокировать User Agents используя Nginx
          • Денис к записи Как включить EPEL репозиторий на CentOS
          • Гость к записи Закомментировать/Раскомментировать строки vi/vim в Unix/Linux
          • Sergey к записи Установка и настройка OpenVPN сервера на Debian/Ubuntu/Linux Mint

          Источник

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