【问题标题】:Shell - How to deal with find -regex?Shell - 如何处理 find -regex?
【发布时间】:2013-11-07 15:58:18
【问题描述】:

我需要在一个目录中查找所有以“课程”开头的子目录,但它们有下一个版本。例如

course1.1.0.0
course1.2.0.0
course1.3.0.0

那么我应该如何修改我的命令,让它给我正确的目录列表呢?

find test -regex "[course*]" -type d

【问题讨论】:

    标签: regex shell find


    【解决方案1】:

    你可以这样做:

    find test -type d -regex '.*/course[0-9.]*'
    

    它将匹配名称为 course 的文件加上一定数量的数字和点。

    例如:

    $ ls course*
    course1.23.0  course1.33.534.1  course1.a  course1.a.2
    $ find test -type d -regex '.*course[0-9.]*'
    test/course1.33.534.1
    test/course1.23.0
    

    【讨论】:

    • 完全是我想要的。谢谢。
    【解决方案2】:

    您需要删除括号,并为正则表达式使用正确的通配符语法 (.*):

    find test -regex "course.*" -type d
    

    您还可以使用更熟悉的 shell 通配符语法,通过使用 -name 选项而不是 -regex

    find test -name 'course*' -type d
    

    【讨论】:

    • 感谢您的评论。更通用,但有用且很高兴知道 -name 可以提供帮助。 +1
    【解决方案3】:

    我建议使用正则表达式来精确匹配版本号子目录:

    find . -type d -iregex '^\./course\([0-9]\.\)*[0-9]$'
    

    测试:

    ls -d course*
    course1.1.0.0   course1.1.0.5   course1.2.0.0   course1.txt
    
    find . -type d -iregex '^\./course\([0-9]\.\)*[0-9]$'
    ./course1.1.0.0
    ./course1.1.0.5
    ./course1.2.0.0
    

    更新:要准确匹配[0-9]. 3 次,请使用此查找命令:

    find test -type d -regex '.*/course[0-9]\.[0-9]\.[0-9]\.[0-9]$'
    

    【讨论】:

    • 嗯,这是一个更具体和复杂的答案,但我不明白为什么当我不在我正在寻找子目录的目录中时它不起作用。我有义务通过“cd test”然后直接执行“find.”而不是“find test”......但这是一个不错的建议。 +1
    • @Farah:不知道为什么它不适合你。我也在上面展示了我的输出。您也可以使用:find test -type d -iregex '^\./course\([0-9]\.\)*[0-9]$'
    • 这对我也不起作用,但是当我执行以下操作时它起作用了:find test -type d -regex '.*/course\([0-9]\.\)*[0-9]$'
    • 有没有办法强制使用 [0-9]\.\ 而不是 * 3 次?
    • 是的,这给出了预期的结果,+1。顺便说一句,我想我知道为什么当我不在父目录(即“测试”)中时,您建议的解决方案 find . -type d -iregex '^\./course\([0-9]\.\)*[0-9]$' 不起作用。这是因为findcommand 也给出了路径:test/course5.4.0.0,但是,您使用的是^ 符号,它在开头强加了某种模式。这是正确的:find test -type d -iregex '^test/course\([0-9]\.\)*[0-9]$'
    猜你喜欢
    • 2012-05-12
    • 1970-01-01
    • 2013-11-08
    • 2022-08-18
    • 1970-01-01
    • 2018-11-22
    • 2012-12-24
    • 2010-09-10
    相关资源
    最近更新 更多