Linux удаление файлов определенной даты

How to delete files older than X hours

This will delete of the files older than 1 day. However, what if I need a finer resolution that 1 day, say like 6 hours old? Is there a nice clean way to do it, like there is using find and -mtime?

9 Answers 9

Does your find have the -mmin option? That can let you test the number of mins since last modification:

find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete 

Or maybe look at using tmpwatch to do the same job. phjr also recommended tmpreaper in the comments.

Using —mmin +X returns all files with my find. My fault for not checking this first, but this command just deleted most of my home directory. For me, —mmin -X is the correct argument.

tmpreaper is a fork of tmpwatch. It is safer, and exists as a debian package in the distro. Benefits over find -delete : tmpreaper will not remove symlinks, sockets, fifos, or special files

Point out that $REQUIRED_FILES need to be in quotes (double quotes) and you can use a pattern like: «.txt» for all .txt files or files beginning with a pattern like: «temp-» to delete all files named with temp-

@PaulDixon how to modify this so that $LOCATION and $REQUIRED_FILES can both have multiple values such as dir1 dir2 and *.txt *.tmp ?

@Enissay $LOCATION is a single directory. For multiple extensions you’d probably want to use a pattern with -regex — see stackoverflow.com/questions/5249779/…

Here is the approach that worked for me (and I don’t see it being used above)

$ find /path/to/the/folder -name '*.*' -mmin +59 -delete > /dev/null 

deleting all the files older than 59 minutes while leaving the folders intact.

Better to single-quote ‘*.*’ or the shell will expand it to actual filenames instead of keeping it as a wildcard for find to resolve. This breaks find ‘s recursive operation on subdirs.

Also keep in mind that -name ‘*.*’ will not delete files that have no extension, such as README , Makefile , etc.

You could to this trick: create a file 1 hour ago, and use the -newer file argument.

(Or use touch -t to create such a file).

there is no -older switch (at least in my find command), and that’s what would be needed. -newer doesn’t help.

can you give a touch command that would generate a file 1 hour old that will work on machines that can’t use -mmin? (If you’re on Linux, -mmin is available, if not then date and other commands are also feeble in comparison.)

@iconoclast touch -t $(date -d ‘-1 hour’ +%Y%m%d%H%M.00) test Creates file test that’s always 1 hour old.

To rm files and directories older than file.ext run rm -r `find -maxdepth 1 -not -newer file.ext` . To rm files and directories newer than file.ext do rm -r `find -maxdepth 1 -newer file.ext` . To place file.ext where you want it in time run touch -t $(date -d ‘-1 hour’ +%Y%m%d%H%M.00) file.ext where ‘-1 hour’ specifies «1 hour ago». Credit: xoftl, rovr138, nickf.

 Example 6 Selecting a File Using 24-hour Mode The descriptions of -atime, -ctime, and -mtime use the ter- minology n ``24-hour periods''. For example, a file accessed at 23:59 is selected by: example% find . -atime -1 -print at 00:01 the next day (less than 24 hours later, not more than one day ago). The midnight boundary between days has no effect on the 24-hour calculation. 

If you do not have «-mmin» in your version of «find», then «-mtime -0.041667» gets pretty close to «within the last hour», so in your case, use:

Читайте также:  Astra linux postgresql перезапуск

so, if X means 6 hours, then:

works because 24 hours * 0.25 = 6 hours

Was hopeful because this old UNIX doesn’t have -mmin, but, sadly this is of no help as this old UNIX also does not like fractional values for mtime: find: argument to -mtime must be an integer in the range -2147483647 to 2147483647

If one’s find does not have -mmin and if one also is stuck with a find that accepts only integer values for -mtime , then all is not necessarily lost if one considers that «older than» is similar to «not newer than».

If we were able to create a file that that has an mtime of our cut-off time, we can ask find to locate the files that are «not newer than» our reference file.

To create a file that has the correct time stamp is a bit involved because a system that doesn’t have an adequate find probably also has a less-than-capable date command that could do things like: date +%Y%m%d%H%M%S -d «6 hours ago» .

Fortunately, other old tools can manage this, albeit in a more unwieldy way.

To begin finding a way to delete files that are over six hours old, we first have to find the time that is six hours ago. Consider that six hours is 21600 seconds:

$ date && perl -e '@d=localtime time()-21600; \ printf "%4d%02d%02d%02d%02d.%02d\n", $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]' > Thu Apr 16 04:50:57 CDT 2020 202004152250.57 

Since the perl statement produces the date/time information we need, use it to create a reference file that is exactly six hours old:

$ date && touch -t `perl -e '@d=localtime time()-21600; \ printf "%4d%02d%02d%02d%02d.%02d\n", \ $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]'` ref_file && ls -l ref_file Thu Apr 16 04:53:54 CDT 2020 -rw-rw-rw- 1 root sys 0 Apr 15 22:53 ref_file 

Now that we have a reference file exactly six hours old, the «old UNIX» solution for «delete all files older than six hours» becomes something along the lines of:

$ find . -type f ! -newer ref_file -a ! -name ref_file -exec rm -f "<>" \; 

It might also be a good idea to clean up our reference file.

Источник

Удаление файлов старше n дней в Linux

Пользователи Linux иногда сталкиваются с ситуацией, когда нужно почистить определенный каталог, удалив из него старые, неиспользуемые файлы. Через стандартный проводник это делать далеко не всегда удобно. Но данную процедуру очень просто выполнять через терминал.

По ходу данной статьи мы разберемся с удалением файлов старше определенного количества дней в Ubuntu. Заодно объясним некоторые нюансы этой процедуры.

Читайте также:  Xeon e3 1200 linux driver

Удаление файлов старше n дней в Linux

Для терминала Ubuntu существует специальная команда find, которая отвечает за поиск файлов на компьютере. А с помощью опции -mtime получится найти только те файлы, дата изменения которых старше заданного временного промежутка. В качестве примера возьмем каталог Downloads и срок в 35 дней.

Откройте терминал и запустите следующую команду:

find ~/Downloads -type f -mtime +35

8fsAGtAO1XbSkAAAAASUVORK5CYII=

Вам необязательно действовать напрямую и стирать сразу же все файлы. Их можно отсортировать дополнительно по еще одному признаку, например, по названию или расширению. Для этого есть опция -name, которая прописывается сразу же после директории. Если нужно избавиться только от zip-архивов, то подойдет такая команда:

find ~/Downloads -name «*.zip» -type f -mtime +35 -delete

ByZkw8E2C2n2AAAAAElFTkSuQmCC

Ну и напоследок хотелось бы упомянуть, что при запуске терминала Ubuntu из конкретной папки вручную директорию прописывать не придется. Это можно сделать через стандартное приложение Файлы, если перейти к нужному каталогу, кликнуть правой клавишей мыши по пустому месту и в контекстном меню выбрать пункт Открыть в терминале.

7v5wAAAABJRU5ErkJggg==

Тогда команда для поиска, если она еще нужна, сократится до следующего варианта:

wd2Gmddp20QPQAAAABJRU5ErkJggg==

А для удаления не забудьте в конце дописать опцию -delete:

8f507C0nZQ++gAAAAASUVORK5CYII=

Выводы

По ходу данной статьи мы вкратце объяснили, как можно в конкретном каталоге отыскать файлы старше определенного возраста через терминал Ubuntu, а также как удалить файлы старше n дней linux. Сама по себе процедура довольно простая, но может сэкономить много времени при чистке уже ненужных данных с компьютера.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Как найти и удалить файлы старше конкретной даты в Linux

Как найти и удалить файлы старше конкретной даты в Linux

Хочу в этой теме «Как найти и удалить файлы старше конкретной даты в Linux» рассказать как можно найти и удалить определенные файлы по дате в ОС Linux таких как Debian, Ubuntu или Redhat, Centos. На готовых примера покажу что и как нужно делать.

1. Посмотрим список всех файлов в папке с датой изменения, для этого стоит выполнить команду:

пример использование команды ls -lah для вывода подробной информации о файлах

пример использование команды ls -lah для вывода подробной информации о файлах

2. Чтобы узнать сегодняшнюю дату, нужно выполнить:

# date on Jul 14 04:04:52 EEST 2014

3. Команда что выше не вывела полную дату, можно это исправить:

# ls --full-time total 36576 drwxr-xr-x 8 root root 4096 2014-06-06 07:16:21.000000000 +0300 firefox -rw-r--r-- 1 root staff 37445961 2014-06-06 07:21:16.000000000 +0300 firefox-30.0.tar.bz2

4. Допустим нужно найти файлы и удалить их по определенной дате.

Если нужно найти все файлы свыше 3 дня и после чего удалить их:

# find /home/captain -type f -mtime +3 -exec rm -rf <> \;

Если нужно найти все файлы свыше 90 дней и после чего удалить их:

# find /home/captain -type f -mtime +90 -exec rm -rf <> \;

Если нужно найти все файлы свыше 365 дней и после чего удалить их:

# find /home/captain -type f -mtime +365 -exec rm -rf <> \;

Если нужно найти все файлы свыше 100 дней и после чего удалить их:

# find /home/captain -type f -mtime +100 -exec rm -rf <> \;

Удаление файлов старше N дней

$ find /dir/ -atime +N | xargs rm -f
$ find /dir/ -name "*.jpg" -mtime +N -exec rm -f <> \;

Ключи:
-name — искать по имени файла, при использовании подстановочных образцов параметр заключается в кавычки.
-type — тип искомого: f=файл, d=каталог, l=ссылка (link).
-user — владелец: имя пользователя или UID.
-group — владелец: группа пользователя или GID.
-perm — указываются права доступа.
-size — размер: указывается в 512-байтных блоках или байтах (признак байтов — символ «c» за числом).
-atime — время последнего обращения к файлу.
-ctime — время последнего изменения владельца или прав доступа к файлу.
-mtime — время последнего изменения файла.
-newer другой_файл — искать файлы созданные позже, чем другой_файл.
-delete — удалять найденные файлы.
-ls — генерирует вывод как команда ls -dgils.
-print — показывает на экране найденные файлы.
-exec command <> \; — выполняет над найденным файлом указанную команду; обратите внимание на синтаксис.
-ok — перед выполнением команды указанной в -exec, выдаёт запрос.
-depth — начинать поиск с самых глубоких уровней вложенности, а не с корня каталога.
-prune — используется, когда вы хотите исключить из поиска определённые каталоги.
N — количество дней.

Читайте также:  Linux create raid mdadm

Источник

Delete files older than X days +

Possibly fun when I have files with spaces. E.g a file called «test one» and rm gets fed rm test one . (Which will delete a file called «test» and a file called «one», but not a file called «test one»). Hint: -delete or -print0

As a side note, always quote the argument provided by find to avoid issues with special characters, as mentioned in the answer’s first line. E.g.: find /path/to/files/ -exec somecommand ‘<>‘ \;

4 Answers 4

Be careful with special file names (spaces, quotes) when piping to rm.

There is a safe alternative — the -delete option:

find /path/to/directory/ -mindepth 1 -mtime +5 -delete 

That’s it, no separate rm call and you don’t need to worry about file names.

Replace -delete with -depth -print to test this command before you run it ( -delete implies -depth ).

  • -mindepth 1 : without this, . (the directory itself) might also match and therefore get deleted.
  • -mtime +5 : process files whose data was last modified 5*24 hours ago.

Alternatively, if you want to do the same for all files NEWER than five days: find /path/to/directory/ -mindepth 1 -mtime -5 -delete

Note that every find argument is a filter that uses the result of the previous filter as input. So make sure you add the -delete as the last argument. IE: find . -delete -mtime +5 will delete EVERYTHING in the current path.

Note that this command will not work when it finds too many files. It will yield an error like:

bash: /usr/bin/find: Argument list too long 

Meaning the exec system call’s limit on the length of a command line was exceeded. Instead of executing rm that way it’s a lot more efficient to use xargs. Here’s an example that works:

find /root/Maildir/ -mindepth 1 -type f -mtime +14 | xargs rm 

This will remove all files (type f) modified longer than 14 days ago under /root/Maildir/ recursively from there and deeper (mindepth 1). See the find manual for more options.

Источник

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