简体   繁体   English

linux 查找名称中带有可选字符的文件

[英]linux find files with optional character in their name

suppose I have two files: ac and abc .假设我有两个文件: acabc I want to find a regex to match both files.我想找到一个正则表达式来匹配这两个文件。 Normally I would expect the following regex to work, but it never does:通常我希望以下正则表达式可以工作,但它永远不会:

find ./ -name ab?c

I have tried escaping or not the questionmark, this never seems to work.我试过逃避或不逃避问号,这似乎从来没有奏效。 Normally in the regex documentations I have found;通常在我发现的正则表达式文档中; ? means: previous character repeated 0 or 1 times , but find doesn't seem to understand this.意思是:前一个字符重复了 0 或 1 次,但find似乎不明白这一点。

I have tried this on two different find versions: GNU find version 4.2.31 and find (GNU findutils) 4.6.0我在两个不同的 find 版本上尝试过这个:GNU find version 4.2.31 和 find (GNU findutils) 4.6.0

PS: this works with * , but I specifically would like to match just one optional character . PS:这适用于* ,但我特别想只匹配一个可选字符

find ./ -name a*c

gives

./ac
./abc

The expression passed to -name is not a regex, it is a glob expression.传递给-name的表达式不是正则表达式,而是全局表达式。 A (single) glob expression can't be used for your use case but you can use regular expressions using -regex : (单个)glob 表达式不能用于您的用例,但您可以使用正则表达式-regex

find -regex '.*/ab?c'

Btw, the default regular expression language is Emacs Style as explained here : https://www.emacswiki.org/emacs/RegularExpression .顺便说一句,默认的正则表达式语言是 Emacs 样式,如下所述: https : //www.emacswiki.org/emacs/RegularExpression You can change the regex language using -regextype .您可以使用-regextype更改正则表达式语言。

To match the expression with only one optional character try using or option:仅使用一个可选字符匹配表达式,请尝试使用or选项:

touch abc ac abbc
find . -name "a?c" -or -name "ac"

Gives you only: abc and ac names.只给你: abcac名称。

Generally you can build pretty complex find queries using or and and options =)通常,您可以使用or and选项构建非常复杂的查找查询 =)

The find -name option uses a glob pattern, which is not the same as a regex. find -name选项使用 glob 模式,这与正则表达式不同。 For globs, ?对于球体, ? means any single character.表示任何单个字符。 If you want a character to be optional, you need to use two patterns:如果你想要一个字符是可选的,你需要使用两种模式:

find ./ -name abc -o -name ac

Other answers are good enough to have a solution but knowing find 's -regex option matches on whole entry is essential.其他答案足以提供解决方案,但了解find-regex选项在整个条目上匹配是必不可少的。 So you can't just do a partial match:所以你不能只做部分匹配:

-regex 'ab?c'

You have to use one or two dot-stars:您必须使用一两个点星:

-regex '.*ab?c.*'

Also without wildcards this would be possible using grep :同样没有通配符,这可以使用grep

ls . | grep 'ab\?c' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM