Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursively delete all files except some especific types

Tags:

bash

I want to recursively delete all files in some folders except those who have .gz extension. Normally I use

find /thepath -name "foo" -print0 | xargs -0 rm -rf

to recursively delete all folders named "foo" in the /thepath. But now I wan to add an exclusion option. How that is possible?

For example, the folder structure looks like

 .hiddenfolder
 .hiddenfolder/bin.so
 arc.tar.gz
 note.txt
 sample

So I want to delete everything but keep arc.tar.gz

like image 709
mahmood Avatar asked Dec 30 '13 19:12

mahmood


People also ask

How do you remove all files except some?

Using Extended Globbing and Pattern Matching Operators Also, with the ! operator, we can exclude all files we don't want glob to match during deletion. Let's look at the list of pattern matching operators: ?(pattern-list) matches at least zero and at most one occurrence.

How do I delete all files except a specific file extension?

Microsoft Windows Browse to the folder containing the files. Click the Type column heading to sort all files by the type of files. Highlight all the files you want to keep by clicking the first file type, hold down Shift , and click the last file.

How do you exclude in rm?

A: There is no native exclude option for the rm command in Linux. You can however string some commands together in order to accomplish the same effect. You can exclude files by using any wildcard or globbing patterns.

How do I delete all files from a specific type in Linux?

Using rm Command To remove a file with a particular extension, use the command 'rm'. This command is very easy to use, and its syntax is something like this. In the appropriate command, 'filename1', 'filename2', etc., refer to the names, plus their full paths.


2 Answers

Find and delete all files under /thepath except with name matching *.gz:

# First check with ls -l
find /thepath -type f ! -name '*.gz' -print0 | xargs -0 ls -l

# Ok: delete
find /thepath -type f ! -name '*.gz' -print0 | xargs -0 rm -vf

Oh, and to delete all empty left-over directories:

find /thepath -type d -empty -print0 | xargs -0 rmdir -v
like image 127
grebneke Avatar answered Nov 01 '22 05:11

grebneke


I think

find /thepath -name "foo" ! -name "*.gz" -print0

should produce the correct list of filenames, but check before piping the output to your xargs command to perform the actual deletions.

like image 30
chepner Avatar answered Nov 01 '22 05:11

chepner