简体   繁体   English

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

[英]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. 我有一个MySQL查询,我需要在bash脚本中多次运行。
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. 下一个MySQL命令将具有不同的选择条件。
And other MySQL commands will have deletes instead of selects. 其他MySQL命令将具有删除而不是选择。
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. 我尝试使用bash source命令,但MySQL对此进行了解释,因此我认为这必须是MySQL命令。
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: 更新-bash尝试:

script1: 脚本1:

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

script2: 脚本2:

'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. 连接所需的代码片段,然后将其传递给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.) (要查看sed脚本的作用,请注释掉通往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). 但是,如果您的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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