Mapping file names using the Linux Shell command line

I need a way to match file names in a directory.

For example, I have three files:

CAt_DoG_ZebRa.TXT MOUSE_lion_deer_BIRD.TXT fIsh_biRD_LION.TXT 

I am not a regular expression expert in any way, however I used to use something similar in SnapLogic and Pentaho before:

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

The above will correspond to all file names that contain the words β€œbird” and β€œlion”, the case being ignored and the word order does not matter. Very powerful! Thus, this will correspond to these two:

 MOUSE_lion_deer_BIRD.TXT fIsh_biRD_LION.TXT 

I tried many options above in combination with find and grep, but to no avail. For instance:

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

The above find does not match anything.

Can someone recommend a way to do this?

+6
source share
3 answers
 # ls asdafsdfdBirdasfdfd.txt dasdbirdbfdgdlionb.txt fgdfLionqweBirdaqw.txt # ls | /usr/gnu/bin/grep -i -E '.*(bird.*lion|lion.*bird).*\.txt' dasdbirdbfdgdlionb.txt fgdfLionqweBirdaqw.txt 

trick: when you write some kind of regular expression, looking forward or looking back, doubt it, and either change the other way to write it, or think about whether the regular expression is the right tool for this problem.

+2
source
 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 do not care about the order between these 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 
+7
source

First, does not support PCRE regex engine, so this is the solution for your problem, and (recursive):

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

This solution works with all file names corresponding to birds and lions in any orders.

0
source

Source: https://habr.com/ru/post/979954/


All Articles