Linux delete all old files

Delete Files Older Than One year on Linux

By the time, many files are still on my system and I don’t need them anymore, so how to delete all files that are one year old at least?

1 Answer 1

You can do it with this command

find /path/to/files* -mtime +365 -exec rm <> \; 

/path/to/files* is the path to the files.

-mtime is used to specify the number of days old that the file is. +365 will find files older than 365 days which is one year

-exec allows you to pass in a command such as rm.

Edit Thanks to @Oli note —> you can do it by:

find /path/to/files* -mtime +365 -delete 

You should always quote the <> in -exec (so it reads -exec rm «<>» \; ). This makes sure that spaces are handled properly. And you could just use the -delete function instead of -exec .

@Oli Huh. (What you have said cannot be right, considering that the shell turns «<>» into <> before passing it to find in the first place; then find substitutes for it. Quoting <> is suggested in case < and >themselves may sometimes be treated specially by the shell—which has nothing to do with blank spaces. And often <> doesn’t have to be quoted. I can’t think of any situation, at least when invoking find from a Bourne-style shell, when <> , with nothing inside, appearing by itself as an argument, would have to be quoted. Can you?)

@EliahKagan Yeah, turns out find handles escaping for itself but it’s not a bad habit to be in while scripting. It doesn’t hurt.

@Oli But it doesn’t help, even in principle. If find didn’t handle escaping, «<>» would still have the same effect as <> —just neither would work, instead of both working. That <> and «<>» behave the same isn’t—and cannot be—due to any special feature of find. Confusing what gets expanded by the shell with what gets expanded by some other program is a bad habit. We all make that mistake occasionally, but it’s still a mistake—not a best practice. (One might still quote <> to help humans see it’s not a pattern for brace expansion, but that’s unrelated to word splitting.)

Источник

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

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

Читайте также:  Linux cat grep cut

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

Удаление файлов старше 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.

Источник

find files older than X days in bash and delete

I have a directory with a few TB of files. I’d like to delete every file in it that is older than 14 days. I thought I would use find . -mtime +13 -delete . To make sure the command works as expected I ran find . -mtime +13 -exec /bin/ls -lh ‘<>‘ \; | grep ‘‘ . The latter should return nothing, since files that were created/modified today should not be found by find using -mtime +13 . To my surprise, however, find just spew out a list of all the files modified/created today!

See -daystart option for find. Your find counts exactly 24*13 hours backwards, leaving files which might be 24*13 — 1 minute and later your another find will find those.

Читайте также:  Virtualbox install guest additions oracle linux

Just figured it out! The reason is ls . find finds a directory with mtime +13 and ls simply list all it’s content no matter what mtime the files have (facepalm!).

Always test your find command first by replacing «-delete» with «-print». It may also include the current directory (.) in the result list, which may or may not be what you want.

3 Answers 3

find your/folder -type f -mtime +13 -exec rm <> \; 

Doesn’t work for filenames containing spaces. Either (GNU specific) find -delete or find -print0 | xargs -0 rm

@grebneke: can you back up your statement with examples or facts? find ‘s <> is well-known to be safe regarding spaces and funny symbols in file names.

$ find ./folder_name/* -type f -mtime +13 -print | xargs rm -rf 

The -r switch is useless. Moreover, you’ll run into problems if you have filenames containing spaces or other funny symbols. Use -print0 and xargs -0 . if your utilities support them, otherwise, use @Mindx’s answer. Or, if your find supports it, use the -delete test of find as so: find ./folder_name -type f -mtime +13 -delete .

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

using asterisk find ./folder_name/* is mistake, because shell will expand ‘‘ info all items existent in this folder. When folder keeps extremally huge items (files or directories), it will exceed maximum arguments or max characters for execute command. Better remove ‘‘ signt, this will do the same, without any automated shel expand. but if you need to find specified names, use option -name ‘some*thing’ and give expansion directly to find internals.

Источник

Removing files older than 7 days

As @Jos pointed out you missed a space between name and ‘*.gz’ ; also for speeding up the command use -type f option to running the command on files only.

So the fixed command would be:

find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '<>' \; 

Explanation:

  • find : the unix command for finding files/directories/links and etc.
  • /path/to/ : the directory to start your search in.
  • -type f : only find files.
  • -name ‘*.gz’ : list files that ends with .gz .
  • -mtime +7 : only consider the ones with modification time older than 7 days.
  • -execdir . \; : for each such result found, do the following command in . .
  • rm — ‘<>‘ : remove the file; the <> part is where the find result gets substituted into from the previous part. — means end of command parameters avoid prompting error for those files starting with hyphen.

Alternatively, use:

find /path/to/ -type f -mtime +7 -name '*.gz' -print0 | xargs -r0 rm -- 
-print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. 

Which is a bit more efficient, because it amounts to:

rm file1; rm file2; rm file3; . 

An alternative and also faster command is using exec’s + terminator instead of \; :

find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '<>' + 

This command will run rm only once at the end instead of each time a file is found and this command is almost as fast as using -delete option as following in modern find :

find /path/to/ -type f -mtime +7 -name '*.gz' -delete 

I think when using find to do a batch deletion like all *.gz files, it would be important to make use of -maxdepth . The Find command seems to be recursive by default, and it will search all child directories for a matching pattern. This may be unwanted behavior, so it would be a good idea to use -maxdepth 1

Читайте также:  Linux mkfs ntfs быстрое форматирование

for the completeness: you may also use -delete

find /some/where/ -name '*.log' -type f -mtime +7 -delete 

this way you don’t run a command per file.

This is the best answer. Well done for placing the «-delete» portion at the end of the line. I strongly suggest anyone considering this method reads the man page prior to implementation.

Be careful removing files with find. Run the command with -ls to check what you are removing

find /media/bkfolder/ -mtime +7 -name ‘*.gz’ -ls . Then pull up the command from history and append -exec rm <> \;

Limit the damage a find command can do. If you want to remove files from just one directory, -maxdepth 1 prevents find from walking through subdirectories or from searching the full system if you typo /media/bkfolder / .

Other limits I add are more specific name arguments like -name ‘wncw*.gz’ , adding a newer-than time -mtime -31 , and quoting the directories searched. These are particularly important if you are automating cleanups.

find «/media/bkfolder/» -maxdepth 1 -type f -mtime +7 -mtime -31 -name ‘wncw*.gz’ -ls -exec rm <> \;

Источник

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