简体   繁体   English

使用Linux Shell正则表达式匹配文件名

[英]Match file names using Linux Shell regex

I need a way to match file names in directory. 我需要一种方法来匹配目录中的文件名。

For example I have three files: 例如,我有三个文件:

CAt_DoG_ZebRa.TXT
MOUSE_lion_deer_BIRD.TXT
fIsh_biRD_LION.TXT

I am not regex expert by any means, however I've used something like this in SnapLogic and Pentaho before: 我不是任何正则表达式专家,但我之前在SnapLogic和Pentaho中使用过类似的东西:

(?i).*(?=.*bird)(?=.*lion).*.TXT

The above would match all file names that contain the words 'bird' and 'lion' with case being ignored and the order of the words would not matter. 上面的内容将匹配包含单词'bird'和'lion'的所有文件名,其中case被忽略,单词的顺序无关紧要。 Very powerful! 很强大! So it would match these two: 所以它会匹配这两个:

MOUSE_lion_deer_BIRD.TXT    
fIsh_biRD_LION.TXT

I tried lots of variations of the above in conjunction with find and grep to no avail. 我尝试了上面的很多变化与find和grep一起无济于事。 For example: 例如:

find . -regex ".*/(?i).*(?=.*bird)(?=.*lion).*.TXT"

The above find does not match anything. 以上查找与任何内容都不匹配。

Can anyone recommend a way to do this? 谁能推荐一种方法来做到这一点?

shopt -s globstar   # enable recursive globs
shopt -s nocaseglob # make globs case-insensitive
for file in ./**/*bird*lion*.txt; do
  echo "found: $file"
done

...or, if you didn't care about order between those words: ......或者,如果你不关心这些词之间的顺序:

shopt -s globstar   # enable recursive globs
shopt -s nocaseglob # make globs case-insensitive
shopt -s extglob    # enable extended globbing syntax
for file in ./**/*@(bird*lion|lion*bird)*.txt; do
  echo "found: $file"
done
# ls
asdafsdfdBirdasfdfd.txt      dasdbirdbfdgdlionb.txt       fgdfLionqweBirdaqw.txt   
# ls | /usr/gnu/bin/grep -i -E '.*(bird.*lion|lion.*bird).*\.txt'
dasdbirdbfdgdlionb.txt
fgdfLionqweBirdaqw.txt

a trick: when you writing some regular expression using look ahead or look behind, doubt it, and either change another way to write it or think about whether regular expression is a suitable tool for this problem. 一个技巧:当你使用向前看或者向后看写一些正则表达式时,怀疑它,并且要么改变另一种方式来编写它,要么考虑正则表达式是否适合这个问题的工具。

First, doesn't support PCRE regex engine, so this a solution for your problem, with and (recursive) : 首先, 不支持PCRE正则表达式引擎,所以这是一个解决你的问题的方法,用 (递归):

 bash -c "shopt -s globstar; perl -lne 'print if /i.*bird/i and /i.*lion/i' **"

This solution work with all filenames matching bird and lion, in any orders 此解决方案适用于所有与鸟和狮子匹配的文件名,以任何顺序

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

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