开发者

Finding files without a specific extension

can anyone help me with a regex that will find files that dont have a .tar开发者_如何学JAVA.gz extension

i need it to work in my unix script

for i in <REGEX for non tar.gx files>
do
something
done

thanks


Never, never, never use regexes for the task "match every X that doesn't match Y". Instead, use the trivial regex for X and negate the result.

(In shell expressions, replace == with != , or use grep -v . In Perl, use !~ instead of =~ . In JQuery, use the :not operator, etc. If your API doesn't allow you to do anything else but specify one single regex, beat the vendor over the head with Chomsky's A hierarchy of formal languages.)

Complemented regexes are always either inefficient, unreadable or engine-specific - usually all of the above. Just say no to abuse of regexes, use tools for the tasks they're good at!


In bash, with extglob turned on (which appears to be the default) you can negate a glob by using !(<glob>). So:

for i in !(*.tar.gz)
do
    something
done

If you wanted to match two globs, you'd write for i in *.tar.gz *~. Similarly, you can write for i in !(*.tar.gz|*~) if you want to match all files that are neither gzipped archives nor backup files.


If you don't want to use extended globbing, you can also include a simple test:

for file in *
do
    if [[ $file != *.tar.gz ]]
    then
        something
    fi
done


Another possibility (which illustrates an often-overlooked technique) is simply:

ls | grep -v 'pdf$'|while read i; do echo "i=$i"; done

This is hammer-to-crack-a-nut territory for this particular problem, but if you need to do something with a set of files with slightly complicated selection criteria, this can pay off quite quickly.

And it'd work in any sh-like shell.


you can use find as well...

find . -type f -not -iname "*.tar.gz"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜