当模式匹配段落时,awk / sed提取信息

时间:2016-03-18 09:09:24

标签: awk sed

我想在以CREATE VIEW开头并以“;”结尾的段落中搜索“FROM”模式并将结果保存在csv文件中。例如,如果我有以下文件:

CREATE VIEW view1
AS something  
FROM table1 ,table2 as A, table3 (something FROM table4)  
FROM table5, table6
USING file1
;
CREATE VIEW view2 
FROM table1 ,table2 ,table6 ,table4
something 
something 
FROM table5 ,table7 (something FROM table4 ,table5(this is something FROM table8)
USING file2
;

我希望得到以下结果:

view1;table1
view1;table2
view1;table3
view1;table4
view1;table5
view1;table6
view2;table1
view2;table2
view2;table6
view2;table4
view2;table5
view2;table7
view2;table4
view2;table5
view2;table8

1 个答案:

答案 0 :(得分:1)

我不会假装知道输入文件中FROM后面的语法,所以这里有如何识别视图以及用逗号分隔FROM行,你可以从那里取出:

$ cat tst.awk
BEGIN { FS="[[:space:]]*,[[:space:]]*"; OFS=";" }
sub(/^CREATE VIEW[[:space:]]+/,"") { view = $0 }
sub(/^FROM[[:space:]]+/,"") {
    for (i=1;i<=NF;i++) {
        print view, $i
    }
}

$ awk -f tst.awk file
view1;table1
view1;table2 as A
view1;table3 (something FROM table4)
view1;table5
view1;table6
view2;table1
view2;table2
view2;table6
view2;table4
view2;table5
view2;table7 (something FROM table4
view2;table5(this is something FROM table8)