22

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?

0

4 Answers 4

32

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually the second "name" should be '_*.7z', which will exclude the 7z files starting with "_", in the current form will exclude only a file named (exactly) "_.7z".
Thanks, yeah, I think that's just a long-overlooked typo.
11

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 "*_*"

1 Comment

Thanks for this "[^_]*.7z" its very easy :)
0

It should be

 find . -name "*[^_].7z" 

Comments

0

A quick way given you have bash 4.2.25, is to simply use bash pattern matching to remove all .7z, but the ones having _.7z, like this:

touch a.7z b.7z c.7z d_.7z e_.7z f.txt
rm *[^_].7z

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.