簡體   English   中英

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命令將具有不同的選擇條件。
其他MySQL命令將具有刪除而不是選擇。
但是正則表達式的列表保持不變。
我嘗試使用bash source命令,但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文檔包含任何外殼元字符(如此處的星號),則可能會產生副作用。 在最壞的情況下,可能將其拆分為帶引號的部分和不帶引號的部分。

...或者,使用稍微愚蠢的解決方法將其撤防:

#!/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