2017-05-09 67 views
0

我有一個包含SQL的文件,它有幾個創建表命令,後面跟着一些表/列的註釋。文件看起來像這樣需要grep來自SQL文件的所有評論

create table abc 
(col1, ..,..); 

comment on table abc is 'This is a single line comment'; 
comment on column abc.col1 is 'This is a multi-line comment. 
One more line of description here'; 
comment on column abc.col2 is 'This is a single line comment'; 

create table mno 
(col1, ..,..); 

comment on table mno is 'This is a multi-line comment. 
One more line of description here'; 
comment on column mno.col1 is 'This is a single line comment'; 
collect statistics on mno column (column1); 

簡單的grep命令無法捕獲多行註釋。我知道,我需要打印所有以「評論」文本開頭的行,直到第一次出現「;」包含多行註釋這也意味着要在不以「評論」語句開頭的行之間打印。

在此先感謝您的任何建議。

+0

你可以發佈一些你已經做過的嘗試嗎? –

回答

1

在一部開拓創新的格式:

awk -v RS=';' '/comment on.*/' sqlfile 

或在單次行:

awk -v RS=';' '/comment on.*/{$1=$1;print $0}' sqlfile 
+0

謝謝@PS。 ;它給了我完全我想要的o/p :) –

0

我會用這個範圍的sed。

此命令的伎倆:

sed -e 's/comment\(.*\);/\1/' sql.txt 

請與您的實際文件名替換sql.txt中。

+0

感謝您的回答。它沒有給我正確的o/p,但感謝您及時的建議:) –

+0

你在得到什麼?知道這將幫助大家幫助你 –

0

也許你可以嘗試刪除換行符,然後更換;用換行:

$ cat /tmp/test | tr -d '\n' | tr ';' '\n' | grep '^[[:space:]]*comment on' 
comment on table abc is 'This is a single line comment' 
comment on column abc.col1 is 'This is a multi-line comment.One more line of description here' 
comment on column abc.col2 is 'This is a single line comment' 
comment on table mno is 'This is a multi-line comment.One more line of description here' 
comment on column mno.col1 is 'This is a single line comment' 
1

這可能會爲你工作(GNU SED):

sed '/^comment on.*;\s*$/b;/^comment on/!d;:a;n;/;\s*$/!ba' file 

打印單行註釋。刪除不是多行註釋的其他行。

這可能是更簡潔寫成:

sed '/^comment on/{:a;/;\s*$/{p;d};n;ba};d' file 
+0

這可以在沒有分支命令('b')的情況下完成......如果註釋在一行末尾包含';',這可能會中斷。在';'之前加''o47'是正確的!無論如何,你的腳本似乎比我的腳本更快。 –

+0

謝謝@potong,感謝您寶貴的時間和幫助。我接受了PS的答覆。因爲我覺得它最簡單。 –

1

簡單地說,使用

sed -ne '/comment/{:;/\o47;$/!{n;b};p}' < path/filename 

其中:

  • 如果線路不包含comment
    • 設定一個分支點
    • 檢查,如果符合';
    • 如果其他
      • 打印當前緩衝終止並獲得下一行
      • 分支之前設置分支點
    • 打印當前緩衝區
  • -n sw癢,放下一切

這將打印單行註釋多行註釋:

comment on table abc is 'This is a single line comment'; 
comment on column abc.col1 is 'This is a multi-line comment. 
One more line of description here'; 
comment on column abc.col2 is 'This is a single line comment'; 
comment on table mno is 'This is a multi-line comment. 
One more line of description here'; 
comment on column mno.col1 is 'This is a single line comment'; 

合併線

如果你希望所有的評論中就行,你必須合併線在保持緩衝區中,通過使用N而不是n,然後用空格替換換行符:

sed -ne '/comment/{:;/\o47;\s*$/!{N;b};s/\n\s*/ /;p}' <file 
+0

作爲[@potong](http://stackoverflow.com/a/43863821/1765658)建議,可以在';'和'$'之間添加'\ s *'來獲取包含尾部空格的行:'sed -n '/ comment/{:;/\ o47; \ s * $ /!{n; b}; p}' –

+0

Thanks @F。 Hauri,它給了我需要的輸出。我正在使用PS提供的答案。 (使用awk)由於簡單。很高興知道sed可以做同樣的事情:) –

+0

@PankajK通過使用[tag:sed],你也可以合併行;-)我更喜歡一般''sed'到'awk',因爲它更輕,更頻繁安裝在糟糕的配置。 –

相關問題