Find all old files linux

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

Очень важно находить и очищать старые файлы, которые больше не нужны через определенный промежуток времени.

Вот быстрый способ сделать это.

В этом кратком руководстве вы узнаете, как находить и удалять файлы старше X дней в Linux и Unix-подобных операционных системах.

Найти и удалить файлы старше X дней в Linux

Отказ от ответственности: вы должны быть очень осторожны при выполнении этих команд.

Эти команды не запрашивают подтверждения перед удалением файлов.

Он просто удалит файлы после нажатия клавиши ENTER. Так что будьте очень осторожны!

Сначала давайте узнаем файлы старше X дней, например 30 дней.

Чтобы сделать так, просто:

Вышеупомянутая команда найдет и отобразит старые файлы старше 30 дней. Вот,

dot (.) – Представляет текущий каталог.
-mtime – представляет время изменения файла и используется для поиска файлов старше 30 дней.
-print – отображает старые файлы

Если вы хотите искать файлы в определенном каталоге, просто замените точку на путь папки.

Например, чтобы узнать файлы, которые старше 30 дней в каталоге / home / sk / Downloads, просто запустите:

Теперь, чтобы удалить файлы, запустите любую из следующих команд.

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

Перед выполнением этих команд будьте осторожны и дважды проверьте их.

Периодически удаляйте старые файлы, если они не нужны через регулярные промежутки времени, или резервируют их на любые внешние диски и освобождают место на диске.

Вы можете использовать свободное пространство для любых других полезных целей.

Источник

How to Delete Files Older than 30 days in Linux

This is the best practice to remove old unused files from your server. For example, if we are running daily/hourly backup of files or database on the server then there will be much junk created on the server. So clean it regularly. To do it you can find older files from the backup directory and clean them.

This article describe you to how to find and delete files older than 30 days. Here 30 days older means the last modification date is before 30 days.

1. Delete Files older Than 30 Days

You can use the find command to search all files modified older than X days. And also delete them if required in single command.

First of all, list all files older than 30 days under /opt/backup directory.

Verify the file list and make sure no useful file is listed in above command. Once confirmed, you are good to go to delete those files with following command.

2. Delete Files with Specific Extension

Instead of deleting all files, you can also add more filters to find command. For example, you only need to delete files with “.log” extension and modified before 30 days.

Читайте также:  Установка виндовс 10 поверх линукс минт

For the safe side, first do a dry run and list files matching the criteria.

Once the list is verified, delete those file by running the following command:

Above command will delete only files having .log extension and last modification date is older than 30 days.

3. Delete Old Directory Recursively

Using the -delete option may fail, if the directory is not empty. In that case we will use Linux rm command with find command.

The below command will search all directories modified before 90 days under the /var/log directory.

Here we can execute the rm command using -exec command line option. Find command output will be send to rm command as input.

Conclusion

In this tutorial, you have learned to search and delete files modified older than specific days in Linux command line.

Источник

Команда find в Linux

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

В этой статье мы поговорим о поиске с помощью очень мощной команды find Linux, подробно разберем ее синтаксис, опции и рассмотрим несколько примеров.

Основная информация о Find

Find — это одна из наиболее важных и часто используемых утилит системы Linux. Это команда для поиска файлов и каталогов на основе специальных условий. Ее можно использовать в различных обстоятельствах, например, для поиска файлов по разрешениям, владельцам, группам, типу, размеру и другим подобным критериям.

Утилита find предустановлена по умолчанию во всех Linux дистрибутивах, поэтому вам не нужно будет устанавливать никаких дополнительных пакетов. Это очень важная находка для тех, кто хочет использовать командную строку наиболее эффективно.

Команда find имеет такой синтаксис:

find [ папка] [ параметры] критерий шаблон [действие]

Папка — каталог в котором будем искать

Параметры — дополнительные параметры, например, глубина поиска, и т д

Критерий — по какому критерию будем искать: имя, дата создания, права, владелец и т д.

Шаблон — непосредственно значение по которому будем отбирать файлы.

Основные параметры команды find

Я не буду перечислять здесь все параметры, рассмотрим только самые полезные.

  • -P никогда не открывать символические ссылки
  • -L — получает информацию о файлах по символическим ссылкам. Важно для дальнейшей обработки, чтобы обрабатывалась не ссылка, а сам файл.
  • -maxdepth — максимальная глубина поиска по подкаталогам, для поиска только в текущем каталоге установите 1.
  • -depth — искать сначала в текущем каталоге, а потом в подкаталогах
  • -mount искать файлы только в этой файловой системе.
  • -version — показать версию утилиты find
  • -print — выводить полные имена файлов
  • -type f — искать только файлы
  • -type d — поиск папки в Linux

Критерии

Критериев у команды find в Linux очень много, и мы опять же рассмотрим только основные.

  • -name — поиск файлов по имени
  • -perm — поиск файлов в Linux по режиму доступа
  • -user — поиск файлов по владельцу
  • -group — поиск по группе
  • -mtime — поиск по времени модификации файла
  • -atime — поиск файлов по дате последнего чтения
  • -nogroup — поиск файлов, не принадлежащих ни одной группе
  • -nouser — поиск файлов без владельцев
  • -newer — найти файлы новее чем указанный
  • -size — поиск файлов в Linux по их размеру
Читайте также:  Windows грузится изображения нет

Примеры использования

А теперь давайте рассмотрим примеры find, чтобы вы лучше поняли, как использовать эту утилиту.

1. Поиск всех файлов

Показать все файлы в текущей директории:

2. Поиск файлов в определенной папке

Показать все файлы в указанной директории:

Искать файлы по имени в текущей папке:

Не учитывать регистр при поиске по имени:

find . -iname «test*»

3. Ограничение глубины поиска

Поиска файлов по имени в Linux только в этой папке:

find . -maxdepth 1 -name «*.php»

4. Инвертирование шаблона

Найти файлы, которые не соответствуют шаблону:

find . -not -name «test*»

5. Несколько критериев

Поиск командой find в Linux по нескольким критериям, с оператором исключения:

find . -name «test» -not -name «*.php»

Найдет все файлы, начинающиеся на test, но без расширения php. А теперь рассмотрим оператор ИЛИ:

find -name «*.html» -o -name «*.php»

6. Несколько каталогов

Искать в двух каталогах одновременно:

find ./test ./test2 -type f -name «*.c»

7. Поиск скрытых файлов

Найти скрытые файлы:

8. Поиск по разрешениям

Найти файлы с определенной маской прав, например, 0664:

find . type f -perm 0664

Найти файлы с установленным флагом suid/guid:

find / -perm 2644

find / -maxdepth 2 -perm /u=s

Поиск файлов только для чтения:

find /etc -maxdepth 1 -perm /u=r

Найти только исполняемые файлы:

find /bin -maxdepth 2 -perm /a=x

9. Поиск файлов в группах и пользователях

Найти все файлы, принадлежащие пользователю:

find . -user sergiy

Поиск файлов в Linux принадлежащих группе:

find /var/www -group developer

10. Поиск по дате модификации

Поиск файлов по дате в Linux осуществляется с помощью параметра mtime. Найти все файлы модифицированные 50 дней назад:

Поиск файлов в Linux открытых N дней назад:

Найти все файлы, модифицированные между 50 и 100 дней назад:

find / -mtime +50 –mtime -100

Найти файлы измененные в течении часа:

11. Поиск файлов по размеру

Найти все файлы размером 50 мегабайт:

От пятидесяти до ста мегабайт:

find / -size +50M -size -100M

Найти самые маленькие файлы:

find . -type f -exec ls -s <> \; | sort -n -r | head -5

find . -type f -exec ls -s <> \; | sort -n | head -5

12. Поиск пустых файлов и папок

find /tmp -type f -empty

13. Действия с найденными файлами

Для выполнения произвольных команд для найденных файлов используется опция -exec. Например, выполнить ls для получения подробной информации о каждом файле:

find . -exec ls -ld <> \;

Удалить все текстовые файлы в tmp

find /tmp -type f -name «*.txt» -exec rm -f <> \;

Удалить все файлы больше 100 мегабайт:

find /home/bob/dir -type f -name *.log -size +100M -exec rm -f <> \;

Выводы

Вот и подошла к концу эта небольшая статья, в которой была рассмотрена команда find. Как видите, это одна из наиболее важных команд терминала Linux, позволяющая очень легко получить список нужных файлов. Ее желательно знать всем системным администраторам. Если вам нужно искать именно по содержимому файлов, то лучше использовать команду grep.

Источник

How To Find The Oldest File In A Directory Tree In Linux

The other day a fellow Linux user asked me how to find the oldest file in a directory from command line in Linux. We could tell the oldest file in a directory by using the date and time stamps in GUI mode. But, I don’t know how to find it from the command line. Fortunately, I found this solution after a bit of digging in Google. If you ever wondered how to find the oldest file in a directory or in the entire file system, read on. It is not that difficult.

Find the oldest file in a directory tree in Linux

To find the oldest file in a directory, for example /home/sk/ostechnix/, run:

Let us break down this command and see what each command line argument does.

  • find — Search for files in a directory hierarchy.
  • /home/sk/ostechnix/ — Search location.
  • type -f — Searches only the regular files.
  • -printf ‘%T+ %p\n’ — Prints the file’s last modification date and time in separated by + symbol. (Eg. 2015-07-22+13:42:40.0000000000). Here, %p indicates the file name. \n indicates new line.
  • sort | head -n 1 — The sort command sorts the output and sends the output to head command to display the oldest file. Here, -n 1 indicates only one file i.e oldest file.
Читайте также:  Как поставить гугл windows

As you might already know, Explainshell helps you to find what each part of a Linux command does.

The above command returned the following output:

As you see in the above output, Absolute FreeBSD_ 2nd Edition.pdf is the oldest file in /home/sk/ostechnix/ directory.

Please note that Linux doesn’t find the oldest file by using the file creation date. Instead, it uses the file modification date to find it.

Likewise, to find the top five oldest files in a given directory, just run:

Sample output:

The oldest file will be displayed first.

To find the oldest file in the entire root (/) file system, run:

Update:

A fellow Linux user has pointed out how to find the oldest or newest files in a directory in the comment section below. It is much easier than my method.

To find out the oldest file in a directory, go to that directory and run:

To find out the newest file in a directory:

Источник

How To Find And Delete Files Older Than X Days In Linux

It is always recommended to find and cleanup your old files which are no longer necessary after a certain period of time. This will save you some disk space. If you didn’t clean your old files yet, here is a quick way to do that. This brief tutorial walk you through how to find and delete files older than X days in Linux and Unix-like operating systems.

Disclaimer:

You should be extremely careful while running the following commands. These commands will not ask you any confirmation before deleting the files. It will simply delete the files once you hit the ENTER key. So be very careful and double check the files you’re about to delete.

Find and delete files older than X days in Linux

First, let us find out the files older than X days, for example 30 days.

To do, so, just run:

The above command will find and display the older files which are older than 30 day in the current working directorys.

  • dot (.) — Represents the current directory.
  • -mtime — Represents the file modification time and is used to find files older than 30 days.
  • -print — Displays the older files

If you want to search files in a specific directory, just replace the dot with the folder path.

For example, to find out the files which are older than 30 days in /home/sk/Downloads directory, just run:

Sample output:

Find files older than 30 days in Linux

Now, run any one of the following command to delete the files which are not required anymore. Again, I warn you that these commands will delete the files immediately once you hit ENTER button. Please be cautious and double check before running these commands.

Also Read:

Conclusion

Delete old files periodically if they are not necessary at regular intervals, or backup them to any external drives and free up disk space. You can use the free space for any other useful purposes.

Источник

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