如何打印所有文字,直到它看到';'通过awk?

时间:2016-07-07 08:10:41

标签: awk

你能帮我用awk解析这个文本吗? 正如您在结果中看到的那样,只显示第一行SQL语句,但我想打印所有SQL语句,直到它以&#39 ;;'结束。 我想我应该为此做一个循环,但我不知道该怎么做。

由于某些原因,应保留awk代码(前4行代码)。

/\] / {

getline;
getline;

if ( index($0,"update ") ) {

数据

-- [1] Thu Nov 21 21:59:10 2013

update owner.table_name t 
set col1 = '2222',
col2='111111',
col3='111111',
col4='111111',
col5='111111',
col6='111111';

-- [1] Sat Nov 23 21:11:19 2015

update owner2.table_name2 t 
set col1 = '2222',
col2='111111',
col6='111111';

AWK

/\] / {

getline;
getline;

if ( index($0,"update ") ) {

splitHipen=$2;
split(splitHipen,splitHipenArr,".");

TABLE_OWNER=splitHipenArr[1];
TABLE_NAME=splitHipenArr[2];
DML=$1;

if(u||index($0,"update ")) { u=1; SQL_STATEMENT=$0; }
if(index($0,";") && u) {u=0;print ""}

printf "%s#%s#%s#%s#\n", TABLE_OWNER,TABLE_NAME,DML,SQL_STATEMENT;             

}

}

当前结果

owner#table_name#update#update owner.table_name t #
owner2#table_name2#update#update owner2.table_name2 t #

所需的输出

owner#table_name#update#update owner.table_name t set col1 = '2222', col2='111111', col3='111111', col4='111111', col5='111111', col6='111111' #
owner2#table_name2#update#update owner2.table_name2 t set col1 = '2222', col2='111111', col6='111111' #

2 个答案:

答案 0 :(得分:2)

<强>替换

if(index($0,";") && u) {u=0;print ""}

while(getline > 0){SQL_STATEMENT = SQL_STATEMENT " "$0;if(index($0,";")) break}

输出

owner#table_name#update#update owner.table_name t  set col1 = '2222', col2='111111', col3='111111', col4='111111', col5='111111', col6='111111';#
owner2#table_name2#update#update owner2.table_name2 t  set col1 = '2222', col2='111111', col6='111111';#

答案 1 :(得分:1)

awk '
/^update/,/;$/ {     # between "update" and ";" do
  if($0~/^update/) { # if it starts with update, get the owner#table_name
    foo=$2"#";       # end with "#"
    gsub(/\./,"#",foo) 
  } foo=foo""substr($0,1,length($0))" " # build the output variable
} 
/;$/ {  # print the variable ofter ; 
  print foo
}
' test3.in