sti*_*oob 3 find regular-expression
命令-name
选项需要什么样的正则表达式语法find
?我的印象是它与 for 相同,-regex
但似乎并非如此。
$ mkdir test && cd test
$ touch .sw.
$ touch .swp
$ touch .abc.swo
$ touch notswap.py
$ find . -name "*sw." -type f
./.sw.
$ find . -name "*sw*" -type f
./notswap.py
./.sw.
./.swp
./.abc.swo
$ find . -regex ".*sw." -type f
./.sw.
./.swp
./.abc.swo
Run Code Online (Sandbox Code Playgroud)
FWIW,我知道-regex
匹配整个路径并且-name
只匹配文件名的基数。我希望很明显,这不是这里的问题。作为一个更具体的问题,如何使用该选项匹配以.swx
wherex
可以是任何字符结尾的所有文件-name
。
元信息:
$ find --version
find (GNU findutils) 4.5.11
...
$ echo $0
bash
Run Code Online (Sandbox Code Playgroud)
-name pattern
Base of file name (the path with the leading directories
removed) matches shell pattern pattern. Because the leading
directories are removed, the file names considered for a match
with -name will never include a slash, so `-name a/b' will
never match anything (you probably need to use -path instead).
A warning is issued if you try to do this, unless the
environment variable POSIXLY_CORRECT is set. The
metacharacters (`*', `?', and `[]') match a `.' at the start
of the base name (this is a change in findutils-4.2.2; see
section STANDARDS CONFORMANCE below). To ignore a directory
and the files under it, use -prune; see an example in the
description of -path. Braces are not recognised as being
special, despite the fact that some shells including Bash
imbue braces with a special meaning in shell patterns. The
filename matching is performed with the use of the fnmatch(3)
library function. Don't forget to enclose the pattern in
quotes in order to protect it from expansion by the shell.
Run Code Online (Sandbox Code Playgroud)
它使用 shell 模式而不是正则表达式。
来源: find(1)
来自name下的 GNU 手册:
以下是搜索名称与特定模式匹配的文件的方法。有关这些测试的模式参数的说明,请参阅 Shell 模式匹配。
find 和 locate 可以将文件名或文件名的一部分与 shell 模式进行比较。Shell 模式是一个字符串,其中可能包含以下特殊字符,这些字符称为通配符或元字符。
您必须引用包含元字符的模式以防止 shell 自行扩展它们。双引号和单引号都有效;用反斜杠转义也是如此。
*
?
[string]
\
斜杠字符在 shell 模式匹配中没有特殊意义, find 和 locate 这样做,不像在 shell 中,通配符不匹配它们。因此,模式“foo bar”可以匹配文件名“foo3/bar”,模式“./sr sc”可以匹配文件名“./src/misc”。
如果您想使用 'locate' 命令定位某些文件但不需要查看完整列表,您可以使用 '--limit' 选项仅查看少量结果,或使用 '--count' 选项只显示匹配的总数。
回答你的问题:
find . -name "*.sw?" -type f
Run Code Online (Sandbox Code Playgroud)