Adobe
Adobe

Reputation: 13467

Bash regular expressions

How to delete all files in the current dir - but not those which have 1.65 in the title?

I tried to capture such files with

*[^1][^\.][^6][^5]*
*[^\(1\.65\)]*

(one can press Alt-* to expand the regexp)

but it doesn't work. Here's a code for experiments:

touch foo1.65bar \#bla1.66 qbit0.65t 1.65boris notRelated@All 

Upvotes: 1

Views: 868

Answers (3)

Ludovic Kuty
Ludovic Kuty

Reputation: 4954

You could use a regex like the one below on a filename with Ruby, Python, Perl, etc. You then have to write a little script or one liner in the chosen language to do the job. It uses negative lookahead. Cfr. Lookahead and Lookbehind Zero-Width Assertions.

^((?!1\.65).)*$

When you want to build a regex that won't match a specific string, you can't use [] because it specifies individual characters, not all of them in sequence. You have to use lookaround constructs.

Upvotes: 0

Peter.O
Peter.O

Reputation: 6856

You can use extended globbing ..(bash 4)

touch a b c foo1.65bar foo1_65bar
ls  
echo ======
shopt -s extglob
rm !(*1.6*)
ls  

Output

a  b  c  foo1_65bar  foo1.65bar
=====
foo1.65bar

Upvotes: 3

thiton
thiton

Reputation: 36049

It is often more reliable and expressive to use find for such jobs:

find -mindepth 1 -maxdepth 1 '(' -type f -and -not -name '*1\.65*' ')' -delete

Upvotes: 4

Related Questions