【问题标题】:Exclude a string from wildcard search in a shell从 shell 中的通配符搜索中排除字符串
【发布时间】:2010-03-23 13:19:07
【问题描述】:

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

假设我有一个文件列表: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

但是如何用字符串来做呢?

塞巴斯蒂安

【问题讨论】:

标签: bash wildcard


【解决方案1】:

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

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

【讨论】:

  • 您可能需要添加 -maxdepth 1 以获得与简单通配符类似的行为
【解决方案2】:

使用 Bash

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

其中第一行表示“设置扩展通配符”,请参阅manual 了解更多信息。

其他一些方法可能是:

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

ls *txt |grep -vi "thomas"

【讨论】:

    【解决方案3】:

    如果您要循环通配符,如果您想排除某些内容,则只需跳过其余的迭代。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2013-06-16
      • 2016-09-16
      • 1970-01-01
      相关资源
      最近更新 更多