Mateusz Chrzaszcz
Mateusz Chrzaszcz

Reputation: 1280

Regexp for matching filenames

I have a files:

first.error.log
second1.log
second2.log
FFFpc.log
TR.den.log
bla.error.log

and I would like to make a pattern that will match all files with error inside of filenames + few additional ones but no more:

For a sole error it would be

 $FILE_PATTERN="*.error*"  

But what if I want to match not only those errors but also all second and FFpc etc?

This does not work:

$FILE_PATTERN="*.error*|^second.*\log$|.*FFPC\.log$" 

Thanks in advance for your help

EDIT:

$FILE_PATTERN is later used by:

find /somefolder -type f -name $FILE_PATTERN

EDIT: THIS FILE_PATTERN is in property file that is later used by bash script.

Upvotes: 2

Views: 105

Answers (5)

konsolebox
konsolebox

Reputation: 75488

FILE_PATTERN=("*.error*" "second.*log" ".*FFPC.log")
ARGS=(-name "$FILE_PATTERN")
for F in "${FILE_PATTERN[@]:2}"; do
    ARGS+=(-o -name "$F")
done
find /somefolder -type f '(' "${ARGS[@]}" ')'

Upvotes: 1

anubhava
anubhava

Reputation: 785156

You need to use find with -regex option:

find -E /somefolder -type f -regex '\./(.*\.error.*|second.*log|.*FFPC\.log)$'

PS: Use -iregex for ignore case matching:

find -E /somefolder -type f -iregex '\./(.*\.error.*|second.*log|.*FFPC\.log)$'

Upvotes: 2

skamazin
skamazin

Reputation: 757

If you're in bash I'm assuming you have to grep. Using grep -E or egrep will allow you to use alternation (ORing your searches)

$ stat * | egrep "(error|second)"
File: `first.error.log'
File: `second1.log'
File: `second2.log'

You could use ls instead of stat but sometimes ls will not give you what you predicted. But considering you're only search for filenames, ls should suffice.

$ ls | egrep "(error|second)"
first.error.log
second1.log
second2.log

You can use command substitution to store the output into a bash variable:

FILE_PATTERN=$(ls | egrep "(error|second)")

Upvotes: 1

Hemang
Hemang

Reputation: 1671

$ ls | grep -i '\(.*error.*\)\|\(^second.*\log$\)\|\(.*FFPC\.log$\)'
bla.error.log
FFFpc.log
first.error.log
second1.log
second2.log

If you wanted to use with find

find /somefolder -type f | grep -i '\(.*error.*\)\|\(^second.*\log$\)\|\(.*FFPC\.log$\)'

Upvotes: 1

Adam Yost
Adam Yost

Reputation: 3625

You were close, theres just a few misplaced symbols.

Here's what I came up with:

.*\.error\..*|^second.*\.log$|.*FF[Pp][Cc]\.log$

here's a demo of a working modification of your regex: http://regex101.com/r/rL3rM1/1

Upvotes: 0

Related Questions