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.
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.
You don't even need to use
rm
in this case if you are afraid. Usefind
: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
andman 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:
So:
You don't need to make an alias for this, because the
trash-cli
package provides a commandtrash
, 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 installedtrash-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 thetrash
command:-xtype f
selects files and symlinks to files, but not folders. To delete .bak folders too, remove that part, and use-execdir
, which avoidscannot trash non-existent
errors for.bak
files inside.bak
directories:If you want to delete all files of a certain type, but only 1 folder "deep" from the current folder:
-maxdepth 2 because the current directory "." counts as the first folder.
Quick Answer:
Delete all files with the considered name or postfix recursively:
find . -name '*.pyc' -type f -delete
Delete all directories with the considered name recursively:
Somewhat less tightly controlled, but in a single line:
[NOTE]:
d
is directory option andf
is file option.If in case you want to check the list before you delete the files, you can echo it.
This will list out the search results that are piped to rm command via xargs. Once you are sure about the list you can drop the echo in above command.
You can list all the files with that extension first before you use
rm
For example,If you get only the files that you want to delete then you can use the
rm