Linux remove files by mask recursive

Linux Delete Folder Recursively Command

rm command syntax to delete directories recursively

The syntax is as follows:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 2m

rm -r dirName
## OR ##
rm -r folderName
## OR ##
rm -rf folderName

Did you know?
Everything is a file in Linux and Unix-like systems. In other words, your pictures, documents, directories/folders, SSD/hard-drives, NIC, USB devices, keyboards, printers, and some network communications all are files.

Examples that examples how to delete folder recursively

In this example, recursively delete data folder in the current home directory:

The specified /home/vivek/data/ will first be emptied of any subdirectories including their subdirectories and files and then data directory removed. The user is prompted for removal of any write-protected files in the directories unless the -f (force) option is given on command line:

To remove a folder whose name starts with a — , for example ‘ —dsaatia ‘, use one of these commands:

We can add the -v option to see verbose outputs. In other words, the rm command will explain what is being done to our files and folders on Linux. For instance:
rm -rfv /path/to/dir1
rm -r -f -v /home/vivek/oldpartpics

Removing folders with names containing strange characters

Your folders and files may have while spaces, semicolons, backslashes and other chracters in Linux. For example:
ls -l
Let us say we have a folder named “ Our Sales Data ” and “ baddir# ” or “ dir2 ;# “. So how do we delete those directories with special names containing strange characters? The answer is simple. We try to enclose our troublesome filename or folder name in quotes. For example:
rm ‘Our Sales Data’
rm -rfv ‘/path/to/Dir 1 ;’
rm -r -f -v «baddir#»
rm a\ long \dir1 \name

Sometimes, we need insert a backslash ( \ ) before the meta-character in your filename or folder name:
rm \$dir1

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Deleting folder recursively command summary

rm command options for removing dirs/folders recursively
Command and options Description
-f Forceful option. Ignore nonexistent files and arguments, never prompt
-r remove directories and their contents recursively
-v Verbose output
rm — ‘-dir1’ Remove a dir/file whoes name start with a ‘ — ‘
rm ./-dir1 Same as above
rm -rfv ‘dir name here’ Enclose your troublesome filename/folder in quotes
rm -rfv \$dirname1 Same as above

See Linux rm(1) command man page or rm command example page for more information:
man rm
rm —help

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Команды для удаления большого количества файлов в Linux

Удаление старых файлов linux по маске чаще всего осуществляется следующим образом:

Веб-сервер указан для примера. Синтаксис очень прост — команда принудительно удалит все файлы с расширением .log в указанном каталоге, при этом удаление будет рекурсивным(-r — recursive) и подтверждения система при этом спрашивать не будет (-f — force).

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

Если rm -rf не помогает — удалять файлы следует в цикле for. Для каждого файла будет отдельная операция удаления и никаких ограничений системы здесь ожидать не приходится.

Синтаксис в простейшем случае может выглядеть так:

for f in /var/log/apache2/*.log; do rm «$f»; done

В цикл for можно добавить любую дополнительную логику.

Удаление старых файлов в Linux по Cron

Логи или другие файлы (сессии РНР) можно удалять как используя циклы (так приходится делать обычно если логов или других файлов накопилось действительно очень много), но если система не запущена или только создается лучше использовать регулярно выполняемое задание Cron, согласно которому с заданной периодичностью будут удаляться файлы определенных типов

# m h dom mon dow command

23 3 * * * find /var/www/web/sites/server-gu.ru/www/var/session/ -type f -mtime 7 -exec rm -f <> \;

В примере удаляются сессии РНР для сайта старше 7 дней.

В цикле то же самое можно сделать так:

for f in /tmp/logs/*.log

find $f -mtime +7 -exec rm <> \;

Приведенное выражение, как и любой другой цикл можно поместить в файл, сделать его исполняемым и с тем же успехом выполнять по Cron

Источник

Recursively delete all files with a given extension [duplicate]

I want to delete all *.o files in a directory and its sub-directories. However, I get an error:

On the other hand, rm *.o works, but it’s not recursive.

2 Answers 2

That is evil: rm -r is not for deleting files but for deleting directories. Luckily there are probably no directories matching *.o .

What you want is possible with zsh but not with sh or bash (new versions of bash can do this, but only if you enable the shell option globstar with shopt -s globstar ). The globbing pattern is **/*.o but that would not be limited to files, too (maybe zsh has tricks for the exclusion of non-files, too).

But this is rather for find :

or (as I am not sure whether -delete is POSIX)

That’s not quite how the -r switch of rm works:

rm has no file searching functionality, its -r switch does not make it descend into local directories and identify files matching the pattern you give it. Instead, the pattern ( *.o ) is expanded by the shell and rm will descend into and remove any directories whose name matches that pattern. If you had a directory whose name ended in .o , then the command you tried would have deleted it, but it won’t find .o files in subdirectories.

What you need to do is either use find :

or, for non-GNU find :

Alternatively, if you are using bash you can enable globstar :

NOTE: all three options will delete directories whose name ends in .o as well, if that’s not what you want, use one of these:

Источник

How do I recursively delete directories with wildcard?

I am working through SSH on a WD My Book World Edition. Basically I would like to start at a particular directory level, and recursively remove all sub-directories matching .Apple* . How would I go about that?

rm -rf .Apple* and rm -fR .Apple*

neither deleted directories matching that name within sub-directories.

5 Answers 5

find is very useful for selectively performing actions on a whole tree.

Here, the -type f makes sure it’s a file, not a directory, and may not be exactly what you want since it will also skip symlinks, sockets and other things. You can use ! -type d , which literally means not directories, but then you might also delete character and block devices. I’d suggest looking at the -type predicate on the man page for find .

To do it strictly with a wildcard, you need advanced shell support. Bash v4 has the globstar option, which lets you recursively match subdirectories using ** . zsh and ksh also support this pattern. Using that, you can do rm -rf **/.Apple* . This is not POSIX-standard, and not very portable, so I would avoid using it in a script, but for a one-time interactive shell action, it’s fine.

I ran into problems using find with -delete due to the intentional behavior of find (i.e. refusing to delete if the path starts with ./, which they do in my case) as stated in its man page:

Delete found files and/or directories. Always returns true. This executes from the current working directory as find recurses down the tree. It will not attempt to delete a filename with a «/» character in its pathname relative to «.» for security reasons.
Depth-first traversal processing is implied by this option.
Following symlinks is incompatible with this option.

Instead, I was able to just do

For your case, it seems that quoting the glob (asterisk, *) was the solution, but I wanted to provide my answer in case anyone else had the similar problem.

NOTE: Previously, my answer was to do the following, but @Wildcard pointed out the security flaws in doing that in the comments.

Источник

How can I recursively delete all files of a specific extension in the current directory?

How do I safely delete all files with a specific extension (e.g. .bak ) from current directory and all subfolders using one command-line? Simply, I’m afraid to use rm since I used it wrong once and now I need advice.

8 Answers 8

You don’t even need to use rm in this case if you are afraid. Use find :

But use it with precaution. Run first:

to see exactly which files you will remove.

Also, make sure that -delete is the last argument in your command. If you put it before the -name *.bak argument , it will delete everything.

See man find and man rm for more info and see also this related question on SE:

First run the command shopt -s globstar . You can run that on the command line, and it’ll have effect only in that shell window. You can put it in your .bashrc , and then all newly started shells will pick it up. The effect of that command is to make **/ match files in the current directory and its subdirectories recursively (by default, **/ means the same thing as */ : only in the immediate subdirectories). Then:

(or gvfs-trash **/*.bak or what have you).

Deleting files is for me not something you should use rm for. Here is an alternative:

As Flimm states in the comments:

The package trash-cli does the same thing as gvfs-trash without the dependency on gvfs.

You don’t need to make an alias for this, because the trash-cli package provides a command trash , which does what we want.

As Eliah Kagan makes clear in extensive comments, you can also make this recursive using find . In that case you can’t use an alias, so the commands below assume you have installed trash-cli . I summarise Eliah’s comments:

This command finds and displays all .bak files and symlinks anywhere in the current directory or its subdirectories or below.

To delete them, append an -exec with the trash command:

-xtype f selects files and symlinks to files, but not folders. To delete .bak folders too, remove that part, and use -execdir , which avoids cannot trash non-existent errors for .bak files inside .bak directories:

Источник

Читайте также:  Xtreme download manager linux установка
Оцените статью