2017-05-09 66 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',因为它更轻,更频繁安装在糟糕的配置。 –

相关问题