7

Running on OS X with a bash script:

sourceFile=`basename $1`
shopt -s nocasematch
if [[ "$sourceFile" =~ "adUsers.txt" ]]; then echo success ; else echo fail ; fi

The above works, but what if the user sources a file called adUsers_new.txt?

I tried:

if [[ "$sourceFile" =~ "adUsers*.txt" ]]; then echo success ; else echo fail ; fi

But the wildcard doesn't work in this case. I'm writing this script to allow for the user to have different iterations of the source file name, which must begin with aduser and have the .txt file extension.

1
  • I believe you need to not quote the RHS of the =~ operator. Commented Aug 21, 2014 at 1:42

2 Answers 2

8

In bash, you can get the first seven characters of a shell variable with:

${sourceFile:0:7}

and the last four with:

${sourceFile:${#sourceFile}-4}

Armed with that knowledge, simply use those expressions where you would normally use the variable itself, something like the following script:

arg=$1
shopt -s nocasematch
i7f4="${arg:0:7}${arg:${#arg}-4}"
if [[ "${i7f4}" = "adusers.txt" ]] ; then
    echo Okay
else
    echo Bad
fi

You can see it in action with the following transcript:

pax> check.sh hello
Bad

pax> check.sh addUsers.txt
Bad

pax> check.sh adUsers.txt
Okay

pax> check.sh adUsers_new.txt
Okay

pax> check.sh aDuSeRs_stragngeCase.pdf.gx..txt
Okay
Sign up to request clarification or add additional context in comments.

1 Comment

That works undoubtedly. But why? Why not just use wildcard matching?
6

=~ operator requires regexp, not wildcard. == accepts wildcards, but they should not be quoted:

if [[ "$sourceFile" == adUsers*.txt ]]; then echo success; else echo fail; fi

You may use a regexp too of course, but it would be a bit overkill:

if [[ "$sourceFile" =~ ^adUsers.*\.txt$ ]]; then echo success; else echo fail; fi

Please note that regexp is open by default (a == .*a.*) while glob is closed (a != *a*).

1 Comment

The RegEx makes it applicable to more situations

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.