0

我有一个像下面这样的文件,里面有很多 SQL 语句。我想在需要时读取特定的 SQL 块。

我的文件.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 $0 }'

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

4

2 回答 2

4

您能否尝试在 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.
于 2020-07-15T07:35:21.007 回答
2

像你这样的数据,其中记录由空行分隔,这就是为什么 awk 具有通过将 RS 设置为 null 来激活的“段落模式”的原因:

$ 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;

When RS is set to the empty string ...有关更多信息,请参见https://www.gnu.org/software/gawk/manual/gawk.html#Multiple-Line

于 2020-07-15T12:52:40.510 回答