2016-07-07 24 views
-2

你能幫我解析awk的這段文字嗎? 正如您在結果中看到的,只顯示第一行SQL語句,但我想打印所有SQL語句直到以';'結尾。 我想我應該做一個循環,但我不知道該怎麼做。如何打印所有文字,直到看到';'通過awk?

由於某些原因,應該保留下面的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

什麼是你想要的輸出? –

回答

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';# 
+0

你節省了我的時間。它適用於我當前的代碼,並且運行良好。 [while ... break]是事情。非常感謝。 – Sigularity

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 
+0

謝謝詹姆斯。你可以讓我知道我可以如何把代碼放在我之前的代碼塊中嗎? – Sigularity

+0

由於我改變了RS,它可能不會像那樣工作。 –

+0

我學到了很多東西。謝謝! – Sigularity

相關問題