从shell中的通配符搜索中排除字符串

时间:2010-03-23 13:19:08

标签: bash wildcard

我正在尝试从文件搜索中排除某个字符串。

假设我有一个文件列表:file_Michael.txt,file_Thomas.txt,file_Anne.txt。

我希望能够写出类似

的内容
ls *<and not Thomas>.txt

给我file_Michael.txt和file_Anne.txt,但不是file_Thomas.txt。

反过来很简单:

ls *Thomas.txt

使用单个字符进行操作也很简单:

ls *[^s].txt

但如何用字符串做?

塞巴斯蒂安

3 个答案:

答案 0 :(得分:16)

您可以使用find执行此操作:

$ find . -name '*.txt' -a ! -name '*Thomas.txt'

答案 1 :(得分:14)

使用Bash

shopt -s extglob
ls !(*Thomas).txt

其中第一行表示“设置扩展通配”,有关详细信息,请参阅manual

其他一些方法可能是:

find . -type f \( -iname "*.txt" -a -not -iname "*thomas*" \)

ls *txt |grep -vi "thomas"

答案 2 :(得分:2)

如果要循环通配符,只要有想要排除的内容,就跳过剩下的迭代。

for file in *.txt; do
    case $file in *Thomas*) continue;; esac
    : ... do stuff with "$file"
done
相关问题