2

I'm trying to use regex inside a file operator to seek for a file where one subdirectory is specified with a regex, but I wonder if it's even possible. I think I tried all the quote and bracket combinations possible. Either I'm missing something here, or a file operator requires a specific path?

I'm not entirely sure. Could somebody please clarify?

What I want to achieve is something like this (this obviously doesn't work because it takes the regex part as name of the subdirectory)

if [[ -r '/agent/[0-9 .]*/bin/run.sh' ]]
1
  • Could you give concrete examples for the name of the variable subdirectory? So that we can check with the regex Commented Jun 22, 2016 at 12:31

3 Answers 3

5

find has a -regex option

-regex pattern

File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3', you can use the regular expression.*bar.' or .*b.*3, but not f.*r3. The regular expressions understood by find are by default Emacs Regular Expressions, but this can be changed with the -regextype option.

if find . -regex '/agent/[0-9 \.]*/bin/run.sh'
Sign up to request clarification or add additional context in comments.

Comments

1

According to the manual, only the =~ operator does regex matching.

There's another way though:

RUNFILES=$( find /agent -name run.sh | grep -e '^/agent/[0-9 .]*/bin/run.sh$' )
if [ -n "$RUNFILES" ]
then
[...]
fi

1 Comment

Thank you for the worked out example. Yours and @pacholik's are both good answers. First answer does it in 1 line though, so will base best answer on that. Thank you again!
0

You can simply use the ls command with a regular expression:

if ls /agent/[0-9\ .]*/bin/run.sh

1 Comment

Seems the regex part is also taken as part of the stringset in this case as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.