【问题标题】:bash find command refuses to find more than one file with wildcardbash find 命令拒绝使用通配符查找多个文件
【发布时间】:2012-03-02 14:29:13
【问题描述】:

我的find 没有按我预期的方式工作。当有多个文件时,它会因错误而停止。

hpek@melda:~/temp/test$ ll
total 16
-rw-r--r--  1 hpek  staff    70B Mar  2 15:16 f1.tex
-rw-r--r--  1 hpek  staff    70B Mar  2 15:17 f2.tex
hpek@melda:~/temp/test$ find . -name *.tex 
find: f2.tex: unknown option
hpek@melda:

如果我删除其中一个文件,那么它可以工作:

hpek@melda:~/temp/test$ rm f1.tex 
hpek@melda:~/temp/test$ find . -name *.tex 
./f2.tex
hpek@melda:~/temp/test$ 

我删除什么文件并不重要。只要通配符给出多个文件,find 就会停止。

【问题讨论】:

    标签: bash find wildcard


    【解决方案1】:

    *.tex 在作为参数发送到命令之前由 bash 扩展。

    find . -name *.tex
    

    在你的情况下相当于

    find . -name f1.tex f2.tex
    

    解决方案:用通配符将"..." 放在参数周围以避免外壳扩展:

    find . -name "*.tex"
    

    这将按预期工作:

    $ find . -name "*.tex"
    ./f1.tex
    ./f2.tex
    

    【讨论】:

    • 我以前从未遇到过find 的任何问题。难道是我的shell出了什么问题!? - 或者在传递参数之前扩展通配符是标准的吗?
    • 嗯,这正是 glob(“通配符”)的工作方式。以 ls 为例:它不知道 *.tex 是什么意思,所以它依赖于 shell 为其进行扩展。 find 在这里是个例外,因为它有更高级的需求,想自己做扩展。
    【解决方案2】:

    您必须引用通配符,以便 bash 不会扩展它们:

    find . -name '*.tex'
    

    现在* 正在被 bash 解释。结果,这是正在执行的实际命令:

    find . -name f1.tex f2.text
    

    【讨论】:

    • 原来是find . -name f1.tex f2.tex,导致出现“未知选项”错误。
    【解决方案3】:

    您的通配符* 在到达find 命令之前被shell 扩展。也就是说,这里是find执行的命令:

    find . -name f1.tex f2.tex
    

    注意,如果你从不同的目录执行命令,你会得到不同的结果,因为通配符会以不同的方式展开。

    为了得到想要的结果,试着像这样转义它:

    find . -name \*.tex 
    

    【讨论】:

      【解决方案4】:

      您想要 find . -name "*.tex" 代替 - 请注意 glob 周围的引号。这里发生的情况是,在您的情况下,您的 shell 正在扩展 glob,然后将结果传递给 find,这导致 find . -name f1.tex f2.tex - 这不是使用 find 的有效方式。

      通过将参数放在引号中,它会按原样传递给 find。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多