Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script to check file name begins with expected string

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.

like image 654
chop Avatar asked Aug 21 '14 01:08

chop


People also ask

How do you check if a string starts with a character in bash?

Introduction – In bash, we can check if a string begins with some value using regex comparison operator =~ .

How do you find the filename in bash?

1) By entering the file name in the terminal: Open the “testfile.sh” in any text editor. Then write the script, save it by pressing “save”. One way is to find a file by asking for a filename from the user in the terminal. Use “-f” to check the file's existence.

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


2 Answers

In bash, you can get the first 7 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
like image 191
paxdiablo Avatar answered Sep 29 '22 22:09

paxdiablo


=~ 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*).

like image 25
Dmitry Alexandrov Avatar answered Sep 29 '22 22:09

Dmitry Alexandrov