List files not matching a pattern?

谁都会走 提交于 2019-11-26 22:22:00
ls | grep -v '\.jar$'

for instance.

Christian

Use egrep-style extended pattern matching.

ls !(*.jar)

This is available starting with bash-2.02-alpha1. Must first be enabled with

shopt -s extglob

As of bash-4.1-alpha there is a config option to enable this by default.

Little known bash expansion rule:

ls !(*.jar)

POSIX defines non-matching bracket expressions, so we can let the shell expand the file names for us.

ls *[!j][!a][!r]

This has some quirks though, but at least it is compatible with about any unix shell.

With an appropriate version of find, you could do something like this, but it's a little overkill:

find . -maxdepth 1 ! -name '*.jar'

find finds files. The . argument specifies you want to start searching from ., i.e. the current directory. -maxdepth 1 tells it you only want to search one level deep, i.e. the current directory. ! -name '*.jar' looks for all files that don't match the regex *.jar.

Like I said, it's a little overkill for this application, but if you remove the -maxdepth 1, you can then recursively search for all non-jar files or what have you easily.

One solution would be ls -1|grep -v '\.jar$'

And if you want to exclude more than one file extension, separate them with a pipe |, like ls test/!(*.jar|*.bar). Let's try it:

$ mkdir test
$ touch test/1.jar test/1.bar test/1.foo
$ ls test/!(*.jar|*.bar)
test/1.foo

Looking at the other answers you might need to shopt -s extglob first.

If your ls supports it (man ls) use the --hide=<PATTERN> option. In your case:

$> ls --hide=*.jar

No need to parse the output of ls (because it's very bad) and it scales to not showing multiple types of files. At some point I needed to see what non-source, non-object, non-libtool generated files were in a (cluttered) directory:

$> ls src --hide=*.{lo,c,h,o}

Worked like a charm.

Another approach can be using ls -I flag (Ignore-pattern).

ls -I '*.jar'
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!