在运行 Yosemite 的 Mac 上,我的桌面上有一个文件目录:
29_foo10.bar
29_foo2.bar
29_foo20.bar
29_foo3.bar
我想定位 foo
之后带有一位数字的文件。当我使用 find -name
时,我可以通过以下方式定位文件选择:
USERNAME=darthvader
DIRECTORY="/Users/$USERNAME/desktop/test"
for theProblem in $(find $DIRECTORY -type f -name '29_foo[0-9].bar'); do
cd $DIRECTORY
echo $theProblem
done
并且我在终端中返回了两个文件(29_foo2.bar
和 29_foo3.bar
),但是当我尝试使用 -regex
时> 它什么也不返回,代码:
for theProblem in $(find $DIRECTORY -type f -regex '29_foo[0-9].bar'); do
cd $DIRECTORY
echo $theProblem
done
我做了一些研究,发现OS X Find in bash with regex digits \d not producing expected results
所以我将代码修改为:
for theProblem in $(find -E $DIRECTORY -iregex '29_foo[0-9].bar'); do
我回来了:
No such file or directory
所以我尝试了:
for theProblem in $(find -E $DIRECTORY -type f -regex '29_foo[0-9].bar'); do
但我仍然得到:
No such file or directory
所以我做了一些进一步的研究,发现 bash: recursively find all files that match a certain pattern并经过测试:
for theProblem in $(find $DIRECTORY -regex '29_foo[0-9].bar'); do
我回来了:
No such file or directory
在兔子洞的更深处,我发现了 How to use regex in file find所以我尝试了:
for theProblem in $(find $DIRECTORY -regextype posix-extended -regex '29_foo[0-9].bar'); do
终端告诉我:
find: -regextype: unknown primary or operator
为什么在 Yosemite 中我无法使用 -regex
定位文件?当我执行 man regex
时,我返回了手册,我的 bash 版本是 3.2.57。那么为什么 -name
可以工作,而 -regex
却不能呢?
最佳答案
您应该在 find
中使用此正则表达式:
find "$DIRECTORY" -type f -regex '.*/29_foo[0-9]\.bar$'
变化是:
.*/
在开始时是必需的,因为每个文件名之前都会有一个DOT
或某个目录路径。- 最后添加了 anchor
$
以避免匹配29_foo3.barn
(如果该文件名也存在的话)。 - DOT 需要在
-regex
中转义,否则它将匹配任何字符。 - 上述
find
命令适用于 OSX-find
以及 gnu-find
。
关于regex - 为什么 -name 可以工作,但我无法在 Mac 终端中使用 -regex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39208465/