Bash script to check filename starts on expected line

Working 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 uploads a file named adUsers_new.txt

?

I tried:

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

      

But the template doesn't work in this case. I am writing this script to allow the user to have different iterations of the source file name, which must start with aduser

and have a file extension .txt

.

+3


source to share


2 answers


In, bash

you can get the first 7 characters of a shell variable with:

${sourceFile:0:7}

      

and the last four:

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

      



Armed with this knowledge, simply use whatever expressions you would normally use this variable in, 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

      

+5


source


Operator

=~

requires a regex, not a wildcard. ==

accepts wildcards but should not be specified:

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

      

You can of course use regexp, but that would be a bit of an overkill:



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

      

Note that regexp is open by default ( a

== .*a.*

), while glob is closed ( a

! = *a*

).

+2


source







All Articles