使用 Shell 脚本从文件中读取 SQL 语句块的更好方法是什么?

what is the better way read a Block of SQL statements from a file using Shell Script?

我有一个如下所示的文件,其中包含许多 SQL 语句。我想在需要时阅读特定的 SQL 块。

MyFile.SQL

#QUERY1
SET ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET VERIFY OFF
SET NUMFORMAT 99999999999999999
Select max(time_created) from test.table1 where cust=1;
EXIT;

#QUERY2
SET ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET VERIFY OFF
SET NUMFORMAT 99999999999999999
Select count(*) from test.table1 where cust=1;
EXIT;


#QUERY3
SET ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET VERIFY OFF
SET NUMFORMAT 99999999999999999
Select count(*) from test.table12 where acct=1;

EXIT;

我正在使用以下命令

x=$(cat test.sql )
echo $x | awk -F'COUNT_QUERY' '{ print [=13=] }'

有人可以帮忙解决这个问题吗?

您能否尝试在 GNU awk.

中使用显示的示例进行跟踪、编写和测试
awk '/^#QUERY2$/{found=1} found; /^EXIT/ && found{exit}'  Input_file

说明: 为以上添加详细说明。

awk '                 ##Starting awk program from here.
/^#QUERY2/{           ##Checking condition if line starts with #QUERY2 then do following.
  found=1             ##Setting found value as 1 here.
}
found;                ##Checking condition if found is SET then print that line.
/^EXIT/ && found{     ##Checking condition if line starts with EXIT and found is SET then do following.
  exit                ##exit from program from here.
}
'  Input_file         ##Mentioning Input_file name here.

像您这样用空行分隔记录的数据是 awk 具有通过将 RS 设置为空来激活的“段落模式”的原因:

$ awk -v RS= '/^#QUERY2\n/' file
#QUERY2
SET ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET VERIFY OFF
SET NUMFORMAT 99999999999999999
Select count(*) from test.table1 where cust=1;
EXIT;

有关详细信息,请参阅 https://www.gnu.org/software/gawk/manual/gawk.html#Multiple-Line 中的 When RS is set to the empty string ...