mysql 从 bash 脚本中的文件读取部分 select 语句

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

我有一个 MySQL 查询,我需要在 bash 脚本中多次 运行。
它有一个很长的正则表达式列表。
我想避免在脚本中多次重复长列表。
代码:

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

下一个 MySQL 命令将有一个不同的 select 标准。
其他 MySQL 命令将删除而不是 selects.
但正则表达式列表保持不变。
我尝试使用 bash 源命令,但 MySQL 对此进行了解释,所以我认为这必须是一个 MySQL 命令。
那么...我该怎么做...

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

提前致谢。
更新 - bash 尝试:

脚本 1:

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

脚本 2:

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

错误:

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

连接您需要的片段,然后将抽签传递给 SQL。

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

(要查看 sed 脚本的作用,请注释掉通往 MySQL 的管道。)

...或等同于

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

但如果您的 here document 包含任何 shell 元字符(如此处的星号),您将 运行 有出现奇怪副作用的风险。在最坏的情况下,可能会将其拆分为引用部分和未引用部分。

...或者,用一个有点愚蠢的解决方法解除它:

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