简体   繁体   中英

mysql read part of select statement from a file in a bash script

I have a MySQL query I need to run multiple times in a bash script.
It has a very long list of regular expressions.
I would like to avoid repeating the long list multiple times in the script.
Code:

select * from tableName where fieldName regexp concat(
... big long list of regular expressions ...
);

The next MySQL command will have a different select criteria.
And other MySQL commands will have deletes instead of selects.
But the list of regular expressions remains the same.
I tried using the bash source command but MySQL interpreted that so I think this has to be a MySQL command.
So ... how can I do this ...

select * from tableName where fieldName regexp concat(
[import regular expression list from file]
);

Thanks in advance.
Update - bash attempt:

script1:

#!/bin/bash
mysql -uusername -ppassword -D dbname -e "select * from tablename where fieldname regexp concat(
source /scripts/script2
);"

script2:

'cat|',
'dog|',
'fish'

error:

ERROR 1054 (42S22) at line 1: Unknown column 'source' in 'where clause'

Concatenate the snippets you need, then pass the lot to SQL.

#!/bin/bash
sed '1s/^/select * from tablename where fieldname regexp concat(/
   $s/$/);/' /scripts/script2 |
mysql -uusername -ppassword -D dbname

(To see what the sed script does, comment out the pipeline to MySQL.)

... or somewhat equivalently

#!/bin/bash
mysql -uusername -ppassword -D dbname <<____HERE
  select * from tablename where fieldname regexp concat($(cat /scripts/script2));
____HERE

but you will run the risk of odd side effects if your here document contains any shell metacharacters (like the asterisk here). In the worst case, maybe split it into a quoted part and an unquoted part.

... Or, disarm it with a slightly silly workaround:

#!/bin/bash
splat='*'
mysql -uusername -ppassword -D dbname <<____HERE
  select $splat from tablename where fieldname regexp concat($(cat /scripts/script2));
____HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM