- Как найти новые файлы в Linux
- Поиск новых файлов в Linux
- Способ 1. Утилита find
- Способ 2. ls
- Выводы
- How to find recently modified files in Linux
- How to check all timestamps of a file?
- 1) Sorting files & folders based on conversion time
- 2) Sorting only folders based on conversion time
- 3) How to find only files that were modified 120 days ago
- 4) How to find only files that were modified in last 15 days
- 5) How to find only files that were modified exactly 10 days ago
- 6) How to find only files that were modified within last 30 Mins
- 7) How to find only the folder’s modified in last 5 Days
- 8) How to find both Files and Folders that were modified in last 15 Days
- 9) How to find modified files and folders starting from a given Date to the latest Date
- 10) How to find all files and folders modified in the Last 24 Hours
- 11) How to find a list of “sh” extension files accessed in the Last 30 Days
- 12) How to find files that have been modified over a period of time
- 13) How to find a list of files created Today
- Closing Notes
- Find files newer than a day and copy
- 5 Answers 5
- man pax
- Bash function to find newest file matching pattern
- 9 Answers 9
- Recursively find all files newer than a given time
- 8 Answers 8
Как найти новые файлы в Linux
Бывают случаи когда нужно посмотреть все новые, недавно измененные или созданные в произвольный период времени файлы в операционной системе Linux. Например, если вы системный администратор и создали файл конфигурации, но потом забыли где его сохранили или же просто хотите проверить не изменял ли кто-либо корневую файловую систему в последнее время.
Операционная система Linux, как всегда, радует множеством способов для решения этой задачи. В этой инструкции мы рассмотрим некоторые из них.
Поиск новых файлов в Linux
Способ 1. Утилита find
Самый распространенный способ найти новые файлы в linux — это воспользоваться утилитой find. В зависимости от ситуации и потребностей утилите передаются различные параметры, можно искать файлы в конкретном диапазоне дат, новее определенной даты или новее определенного файла. Рассмотрим все подробнее.
Можно вывести все файлы в директории и поддиректориях, а затем отсортировать по дате создания:
find /etc -type f -printf ‘%TY-%Tm-%Td %TT %p\n’ | sort -r
Но это слишком громоздко, да и не нужны нам все файлы, нам надо только новые. Следующей командой можно получить все файлы, измененные или созданные за последние 60 минут:
find /etc -type f -mmin -120
Чтобы найти последние измененные файлы linux за последних два дня используете параметр mtime:
find /etc -type f -mtime -2
Если нужно не углубляться в подкаталоги ниже третьего уровня, используйте опцию maxdepth:
find /etc -maxdepth 3 -mtime -2 -type f
Также можно задать диапазон времени, в котором был создан или изменен файл. Например, чтобы посмотреть новые файлы linux за последние семь дней, но исключая последние три дня, наберите:
find /etc -type f -mtime -7 ! -mtime -3
Все эти команды выводят только путь к файлу, но также можно посмотреть атрибуты с помощью опции —exec. Выведем подробные атрибуты новых файлов, выполнив для каждого из них утилиту ls:
find /etc -type f -mmin -120 -exec ls -al <> \;
Предыдущая команда немного сложна и запутана, намного нагляднее для этого использовать утилиту xargs:
find /etc -type f -mmin -120 | xargs ls -l
Утилита find также позволяет найти файлы новее определенного файла. Например, создадим эталонный файл:
И найдем все файлы в корневом каталоге, созданные после его него:
find / -type f -newer /tmp/test
Способ 2. ls
Этот способ намного проще первого, но за простоту мы платим гибкостью. Команда ls тоже умеет сортировать файлы в директории по дате создания. Просто выполните:
В данном случае самый новый файл будет в самом низу. Если файлов очень много можно обрезать вывод с помощью tail:
Выводы
Возможно, это еще не все способы найти новые файлы в Linux, но тут уже есть из чего выбрать лучшее решение для конкретной ситуации. Как показано в этой статье, базовые команды поиска find и ls могут получить еще большую гибкость в объединении с утилитами сортировки sort, а также фильтрации tail и grep.
Источник
How to find recently modified files in Linux
If you are working on thousands of files a day and want to find a list of files that have been modified recently in a directory for certain purposes, this can be done easily using the find command.
The find command is used to search or locate files based on various criteria such as timestamp, file type and file permissions in Linux.
Please refer to our previous article on how to find a directory size in Linux.
In this article, we have included 13 examples for locating files based on timestamp and I hope this article will meet your needs.
In Linux, a file contains three timestamps, which are updated when a file is accessed or modified or replaced.
Types of file timestamps:
- atime: access time or Last access time
- mtime: modify time or Last modification time
- ctime: change time or Last change time
Read the below explanation for better understanding about timestamp.
- atime/amin: The last time the file was accessed by some command or application.
- mtime/mmin: The last time the file’s contents was modified.
- ctime/cmin: The last time the file’s attribute was modified.
How to check all timestamps of a file?
It can be easily seen using ‘stat’ command, which displays all three timestamps of a file.
The common syntax is as follows:
We can use numerical arguments with ‘mtime’. Use “-mtime n” command to return a list of files that were last modified “n” hours ago.
- +n: for greater than n
- -n: for less than n
- n: for exactly n
See the format below for a better understanding.
- -mtime +10: This will find all files that were modified 10 days ago.
- -mtime -10: It will find all files that were modified in the last 10 days.
- -mtime 10: Use this format to find all files that were modified EXACTLY 10 days ago.
1) Sorting files & folders based on conversion time
This can be done by using the ls command with some options as shown below, which sorts the files and folders in reverse order based on the conversion time.
2) Sorting only folders based on conversion time
Use the following format to sort only folders in reverse order based on conversion time.
3) How to find only files that were modified 120 days ago
The below find command will show a list of files that were changed 120 days ago.
4) How to find only files that were modified in last 15 days
The below find command will show a list of files that have changed in the last 15 days:
5) How to find only files that were modified exactly 10 days ago
The below find command will show you a list of files that were changed exactly 10 days ago:
6) How to find only files that were modified within last 30 Mins
The below find command will show a list of files that have changed within the last 30 mins.
7) How to find only the folder’s modified in last 5 Days
This command displays only folders modified within the last 5 days.
8) How to find both Files and Folders that were modified in last 15 Days
This command displays a list of files and folders modified within last 15 days:
9) How to find modified files and folders starting from a given Date to the latest Date
This command allows you to find a list of files and folders that have been modified starting from a given date to the latest date:
10) How to find all files and folders modified in the Last 24 Hours
Alternatively, you can use an easy-to-understand format like the one below to find files and folders that have changed over the past 24 hours.
11) How to find a list of “sh” extension files accessed in the Last 30 Days
This command helps you to find a list of files with “sh” extension accessed in the last 30 days.
12) How to find files that have been modified over a period of time
The below command shows a list of files that have changed in the last 20 minutes.
13) How to find a list of files created Today
This command enables you to find a list of files created today:
Closing Notes
This article explained how to find recently modified files & folders in Linux.
If you have any questions or feedback, feel free to comment below.
Источник
Find files newer than a day and copy
I am working on a script that will copy ONLY files that have been created within the last day off to another folder. The issue I am having is the script I have copies all of the files in the source directory instead of just the files less than a day old.
This is what I have:
The above code copies all of the files in the source directory. If I remove all of the arguments for ‘cp’ then it works:
The above code copies only the newest files as I want but I need to preserve the attributes using the cp arguments.
I have also tried variables and for loops thinking maybe the -exec option was the issue:
However, the above for loop results in the same issue, all files are copied. If I echo $files only the files I need are shown.
How can I get this to work?
5 Answers 5
Some implementations of cp have a -t option, so you can put the target directory before the files:
Note that -a implies —preserve so I removed the latter.
THanks everybody for the help, got it working using a combination of your suggestions:
went with the below code and it works perfectly.
You can use pax for this like:
The command-line bit-by-bit:
-wr — when pax is handed both -w rite and -r ead options it copies. Possibly also useful here. (but not included in the above command)
-l ink — which creates hard-links if at all possible rather than copying the file-data.
-X for restricting pax to the same source device and/or filesystem.
-s/src regex/replace/ — which modifies filenames in-stream
-v erbose — for reporting on files sourced/targeted.
-T — the -T ime option selects files for the target archive (or merely to copy when used with -wr ) based on their /m odification or inode /c hange (or both) times. It defaults to mod time. From.
man pax
. Time comparisons using both file times is useful when pax is used to create a time based incremental archive (only files that were changed during a specified time range will be archived).
A time range is made up of six different fields and each field must contain two digits. The format is:
Where cc is the first two digits of the year (the century), yy is the last two digits of the year, the first mm is the month (from 01 to 12), dd is the day of the month (from 01 to 31), HH is the hour of the day (from 00 to 23), MM is the minute (from 00 to 59), and SS is the seconds (from 00 to 59). The minute field MM is required, while the other fields are optional and must be added in the following order:
The SS field may be added independently of the other fields. Time ranges are relative to the current time, so.
. would select all files with a modification or inode change time of 12:34PM today or later.
Multiple -T time range can be supplied and checking stops with the first match.
. so the 11 up there in my example command is relative to today — it is one less than today’s date — which is the twelfth — and the rest is just a standard «$(date)» format followed by a comma.
. except — and the last thing worth mentioning — I use an absolute path for the target directory — and so should you if you do it. The docs all reference unspecified behavior for relative target paths — and the first time I ever tried using pax I was swearing under my breath for an hour in confusion with all of the weird results until I used an absolute path.
Источник
Bash function to find newest file matching pattern
In Bash, I would like to create a function that returns the filename of the newest file that matches a certain pattern. For example, I have a directory of files like:
I want the newest file that starts with ‘b2’. How do I do this in bash? I need to have this in my
9 Answers 9
The ls command has a parameter -t to sort by time. You can then grab the first (newest) with head -1 .
My personal opinion: parsing ls is only dangerous when the filenames can contain funny characters like spaces or newlines. If you can guarantee that the filenames will not contain funny characters then parsing ls is quite safe.
If you are developing a script which is meant to be run by many people on many systems in many different situations then I very much do recommend to not parse ls .
The combination of find and ls works well for
- filenames without newlines
- not very large amount of files
- not very long filenames
The solution:
Let’s break it down:
With find we can match all interesting files like this:
then using -print0 we can pass all filenames safely to the ls like this:
additional find search parameters and patterns can be added here
ls -t will sort files by modification time (newest first) and print it one at a line. You can use -c to sort by creation time. Note: this will break with filenames containing newlines.
Finally head -1 gets us the first file in the sorted list.
Note: xargs use system limits to the size of the argument list. If this size exceeds, xargs will call ls multiple times. This will break the sorting and probably also the final output. Run
to check the limits on you system.
Note 2: use find . -maxdepth 1 -name «my-pattern» -print0 if you don’t want to search files through subfolders.
Note 3: As pointed out by @starfry — -r argument for xargs is preventing the call of ls -1 -t , if no files were matched by the find . Thank you for the suggesion.
Источник
Recursively find all files newer than a given time
I’m looking for a bash one-liner that lists all files newer. The comparison should take the timezone into account.
But with a time_t instead of a file.
8 Answers 8
You can find every file what is created/modified in the last day, use this example:
for finding everything in the last week, use ‘1 week ago’ or ‘7 day ago’ anything you want
Maybe someone can use it. Find all files which were modified within a certain time frame recursively, just run:
This is a bit circuitous because touch doesn’t take a raw time_t value, but it should do the job pretty safely in a script. (The -r option to date is present in MacOS X; I’ve not double-checked GNU.) The ‘time’ variable could be avoided by writing the command substitution directly in the touch command line.
Given a unix timestamp (seconds since epoch) of 1494500000 , do:
To grep those files for «foo»:
Assuming a modern release, find -newermt is powerful:
or, if you want to specify a time_t (seconds since epoch):
For reference, -newermt is not directly listed in the man page for find. Instead, it is shown as -newerXY , where XY are placeholders for mt . Other replacements are legal, but not applicable for this solution.
From man find -newerXY :
Time specifications are interpreted as for the argument to the -d option of GNU date.
So the following are equivalent to the initial example:
The date -d (and find -newermt ) arguments are quite flexible, but the documentation is obscure. Here’s one source that seems to be on point: Date input formats
Источник