我有一个awk文件 get_PV_sql_from_file.awk :
#! /bin/awk -f
/^CREATE.*VIEW.*PV_/
{
inside_create = 1; print "view found"
}
{
if(inside_create == 1)
{
print $0
}
}
/.*;$/
{
if(inside_create == 1){
inside_create = 0;
}
}
当我运行它时:
awk -f get_PV_sql_from_file.awk test_PV_sql.txt
我在每一行都有“查找”字样:
view found
CREATE FORCE VIEW "POSC"."P3V_SEC_TREES_V" ("BSASC_ID", "BSASC_S", "LV0_K", "LV0_V", "LV1_K", "LV1_V", "LV2_K", "LV2_V", "LV3_K", "LV3_V", "LV4_K", "LV4_V", "LV5_K", "LV5_V") AS
view found
SELECT DISTINCT
view found
B1.BSASC_ID,
view found
B2.BSASC_S,
view found
R_SEC_TREES.LV0_K,
view found
R_SEC_TREES.LV0_V,
...
etc
但是如果我在一行中写下awk文件中的每个命令:
#! /bin/awk -f
/^CREATE.*VIEW.*PV_/ { inside_create = 1; print "view found" }
{ if(inside_create == 1) { print $0 } }
/.*;$/ { if(inside_create == 1) { inside_create = 0; } }
这是正确的:
view found
CREATE FORCE VIEW "POSC"."PV_SEC_MODULES_V" ("BSASC_ID", "MODULE", "ACT") AS
SELECT DISTINCT
B1.BSASC_ID BSASC_ID,
BSASC_PRIVILEGE.GDLN_OR_PRIV_ID MODULE,
BSASC_PRIVILEGE.R_BSASC_PRIV_KIND ACT
...
etc
为什么会这样?我犯了错误?
答案 0 :(得分:1)
您需要将开始操作的模式和左大括号放在同一行上。否则,该模式被视为没有任何操作,因此执行默认操作,即打印该行。然后将下一行的操作视为没有模式,这意味着它匹配每一行。所以写下你的AWK代码:
/^CREATE.*VIEW.*PV_/ {
inside_create = 1; print "view found"
}
{
if(inside_create == 1)
{
print $0
}
}
/.*;$/ {
if(inside_create == 1) {
inside_create = 0;
}
}