There is a directory containing the following files:
.
├── bla-bla-bla1.tar.7z
├── bla-bla-bla2.tar.7z
├── bla-bla-bla3.tar.7z
└── _bla-bla-bla_foo.tar.7z
I need to find and delete all of the files that in the format of *.7z
except _*.7z
I've tried:
find /backups/ -name "*.7z" -type f -mtime +180 -delete
How I can do it?
Finding files by name is probably the most common use of the find command. To find a file by its name, use the -name option followed by the name of the file you are searching for.
We can exclude directories by using the help of “path“, “prune“, “o” and “print” switches with find command. The directory “bit” will be excluded from the find search!
Exclude Files and Directories from a List. When you need to exclude a large number of different files and directories, you can use the rsync --exclude-from flag. To do so, create a text file with the name of the files and directories you want to exclude. Then, pass the name of the file to the --exlude-from option.
Another approach is to use an additional, negated primary with find
:
find /backups/ -name "*.7z" ! -name '_*.7z' -type f -mtime +180 -delete
The simple regex in the other answers is better for your use case, but this demonstrates a more general approach using the !
operator available to find
.
In regular expressions, the ^
operator means "any character except for". Thus [^_]
means "any character except for _". E.g.:
"[^_]*.7z"
So, if your intention is to exclude files starting with _
, your full command line would be:
find /backups/ -name "[^_]*.7z" -type f -mtime +180 -delete
If you'd like to exclude any occerance of _
, you can use the and
and not
operators of find
, like:
find . -name "*.7z" -and -not -name "*_*"
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