如何在 find 命令中使用正则表达式?

新手上路,请多包涵

我有一些用生成的 uuid1 字符串命名的图像。例如 81397018-b84a-11e0-9d2a-001b77dc0bed.jpg。我想使用“查找”命令找出所有这些图像:

 find . -regex "[a-f0-9\-]\{36\}\.jpg".

但它不起作用。正则表达式有问题吗?有人可以帮我解决这个问题吗?

原文由 thoslin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 904
2 个回答
find . -regextype sed -regex ".*/[a-f0-9\-]\{36\}\.jpg"

请注意,您需要在开头指定 .*/ 因为 find 匹配整个路径。

例子:

 susam@nifty:~/so$ find . -name "*.jpg"
./foo-111.jpg
./test/81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
./81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
susam@nifty:~/so$
susam@nifty:~/so$ find . -regextype sed -regex ".*/[a-f0-9\-]\{36\}\.jpg"
./test/81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
./81397018-b84a-11e0-9d2a-001b77dc0bed.jpg

我的查找版本:

 $ find --version
find (GNU findutils) 4.4.2
Copyright (C) 2007 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Built using GNU gnulib version e5573b1bad88bfabcda181b9e0125fb0c52b7d3b
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS() CBO(level=0)
susam@nifty:~/so$
susam@nifty:~/so$ find . -regextype foo -regex ".*/[a-f0-9\-]\{36\}\.jpg"
find: Unknown regular expression type `foo'; valid types are `findutils-default', `awk', `egrep', `ed', `emacs', `gnu-awk', `grep', `posix-awk', `posix-basic', `posix-egrep', `posix-extended', `posix-minimal-basic', `sed'.

原文由 Susam Pal 发布,翻译遵循 CC BY-SA 3.0 许可协议

-regex find 表达式匹配 整个名称,包括当前目录的相对路径。对于 find . 这总是以 ./ 开头,然后是任何目录。

此外,这些是 emacs 正则表达式,除了通常的 egrep 正则表达式之外,它们还有其他转义规则。

如果这些都直接在当前目录下,那么

find . -regex '\./[a-f0-9\-]\{36\}\.jpg'

应该管用。 (我不太确定 - 我无法让计数重复在这里工作。)您可以通过 -regextype posix-egrep 切换到 egrep 表达式:

 find . -regextype posix-egrep -regex '\./[a-f0-9\-]{36}\.jpg'

(请注意,这里所说的一切都是针对 GNU 查找的,我对 BSD 一无所知,这也是 Mac 上的默认设置。)

原文由 Paŭlo Ebermann 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题