我有一个与此类似的问题 Sed/Awk - pull lines between pattern x and y但是,就我而言,我想将每个行 block 输出到单独的文件(以第一个模式命名)。
输入示例:
-- filename: query1.sql
-- sql comments goes here or else where
select * from table1
where id=123;
-- eof
-- filename: query2.sql
insert into table1
(id, date) values (1, sysdate);
-- eof
我希望 bash 脚本生成 2 个文件:query1.sql
和 query2.sql
,其中包含以下内容:
查询1.sql:
-- sql comments goes here or else where
select * from table1
where id=123;
query2.sql:
insert into table1
(id, date) values (1, sysdate);
谢谢
最佳答案
awk '/-- filename/{if(f)close(f); f=$3;next} !/eof/&&/./{print $0 >> f}' input
简要说明,
-- 文件名{if(f)close(f); f=$3;next}
:找到包含文件名的记录,并将其赋值给f
!/eof/&&/./{print $0 >> f}
:如果后续行不包含'eof'也不为空,则将其保存到相应的文件中。
关于bash:模式 x 和 y 之间的单独行 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51416932/