regex - 为什么 -name 可以工作,但我无法在 Mac 终端中使用 -regex?

标签 regex bash macos file find

在运行 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.bar29_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/

相关文章:

python - python中的正则表达式具有已定义的字母数量,但没有更多

用于提取 IP 地址的 Linux bash 脚本

macos - 在Mac上以管理员权限运行可执行文件

javascript - 全面的 RegExp 以删除 JavaScript 注释

php - 将可变格式的电话号码标准化/净化为纯 10 位数字的字符串

regex - Sed 获取 rx : and [space] 之间数据的正则表达式

Bash $0 与终端使用的命令不匹配

bash - 需要帮助替换 bash 脚本中的单引号

macos - 为什么在将 postgres 作为服务运行时无法访问它?

java - 如何在 MacOS 中更改 CurrentJDK 符号链接(symbolic link)