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
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With