Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find files except given name?

Tags:

linux

find

bash

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?

like image 960
user2818137 Avatar asked Sep 26 '13 06:09

user2818137


People also ask

How do I find a file with a certain name?

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.

How do you exclude from find?

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!

How do I exclude a specific file in Linux?

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.


2 Answers

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.

like image 188
chepner Avatar answered Sep 29 '22 16:09

chepner


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 "*_*"
like image 26
shx2 Avatar answered Sep 29 '22 14:09

shx2