Shell - 如何处理find -regex命令?

8

我需要在一个目录中查找以"course"开头且带有版本号的子目录。例如:

course1.1.0.0
course1.2.0.0
course1.3.0.0

那么我应该如何修改命令才能让它给我正确的目录列表?
find test -regex "[course*]" -type d
3个回答

11

你可以做:

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

非常完美,就是我想要的。谢谢。 - Farah

4
您需要去除括号,并使用正则表达式的适当通配符语法(.*):
find test -regex "course.*" -type d

你也可以使用更为熟悉的 shell 通配符语法,只需使用 -name 选项代替 -regex:
find test -name 'course*' -type d

感谢您的评论。更加通用,但是很有用并且知道“-name”可以帮助是很好的。+1 - Farah

1

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

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]$'

@Farah:不确定为什么它对你不起作用。我已经在上面展示了我的输出。你可以使用:find test -type d -iregex '^\./course\([0-9]\.\)*[0-9]$' - anubhava
这对我也不起作用,但是当我执行以下操作时,它可以工作:find test -type d -regex '.*/course\([0-9]\.\)*[0-9]$' - Farah
有没有一种方法可以强制出现 [0-9] . 恰好三次,而不是 *? - Farah
1
是的,那就得到了期望的结果,+1。顺便说一下,我猜我知道为什么你建议的解决方案“find . -type d -iregex '^./course([0-9].)*[0-9]$'”在我不在父目录“test”时不起作用。这是因为find命令也会给出路径:test/course5.4.0.0,但是你使用了“^”符号来强制匹配开头的某个模式。这是正确的方式:find test -type d -iregex '^test/course\([0-9]\.\)*[0-9]$' - Farah
啊,我明白了,是的,我也曾类似地使用过 svn ls - anubhava
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接