Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If string contains in case statement

I'm looking to provide a case statement based on whether a substring is within a filename.

Example Input

mysql_dumps/tpmysqldump-tps_dev_russell_development-information_schema-2014-03-26.sql

Code

    case $DUMPFILE in
         *"tpdata"*)
             database="tpdata";;
         *"tpmrbs"*)
             database="tpmrbs";;
         *"information_schema"*)
             database="information_schema";;
         *"performance_schema"*)
             database="performance_schema";;
         *)
             echo "INVALID FILE";;
    esac
like image 916
Charabon Avatar asked Mar 28 '14 11:03

Charabon


People also ask

Can I use CASE statement in if statement?

The short answer is yes, you can nest an if inside of swtich / case statement (or vice versa).

Which is better IIF or CASE?

For small items with two outcomes, I typically use IIF statements (i.e. If x < a, then 1, else 0) but for longer drawn out statements that can have multiple outcomes, I use CASE.

Can we use if in case statement in SQL?

The CASE statement is SQL's way of handling if/then logic. The CASE statement is followed by at least one pair of WHEN and THEN statements—SQL's equivalent of IF/THEN in Excel.

How do you check if a string contains a word in SQL?

Method 1 - Using CHARINDEX() function This function is used to search for a specific word or a substring in an overall string and returns its starting position of match. In case no word is found, then it will return 0 (zero).


1 Answers

How do you initialize $DUMPFILE? If I run the following, the output is information_schema, which is what I expected...

#!/bin/bash
DUMPFILE=mysql_dumps/tpmysqldump-tps_dev_russell_development-information_schema-2014-03-26.sql
case $DUMPFILE in
    *"tpdata"*)
        database="tpdata";;
    *"tpmrbs"*)
        database="tpmrbs";;
    *"information_schema"*)
        database="information_schema";;
    *"performance_schema"*)
        database="performance_schema";;
    *)
        echo "INVALID FILE";;
esac
echo $database
like image 199
slu Avatar answered Sep 19 '22 15:09

slu