【发布时间】:2013-11-07 15:58:18
【问题描述】:
我需要在一个目录中查找所有以“课程”开头的子目录,但它们有下一个版本。例如
course1.1.0.0
course1.2.0.0
course1.3.0.0
那么我应该如何修改我的命令,让它给我正确的目录列表呢?
find test -regex "[course*]" -type d
【问题讨论】:
我需要在一个目录中查找所有以“课程”开头的子目录,但它们有下一个版本。例如
course1.1.0.0
course1.2.0.0
course1.3.0.0
那么我应该如何修改我的命令,让它给我正确的目录列表呢?
find test -regex "[course*]" -type d
【问题讨论】:
你可以这样做:
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
【讨论】:
您需要删除括号,并为正则表达式使用正确的通配符语法 (.*):
find test -regex "course.*" -type d
您还可以使用更熟悉的 shell 通配符语法,通过使用 -name 选项而不是 -regex:
find test -name 'course*' -type d
【讨论】:
我建议使用正则表达式来精确匹配版本号子目录:
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]$'
【讨论】:
find test -type d -iregex '^\./course\([0-9]\.\)*[0-9]$'
find test -type d -regex '.*/course\([0-9]\.\)*[0-9]$'
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]$'