我有以下格式的数据,我试图在2次出现的字符串之间捕获数据并将其保存在文件中。
create statement
CREATE VIEW `T1` AS SELECT
aa
bb
cc
dd
create statement
CREATE VIEW `T2` AS SELECT
aa
ff
ee
create statement
CREATE VIEW `T3` AS SELECT
aa
bb
ff
..
...
..
我想要以下格式输出:
FileName T1应包含: -
create statement
CREATE VIEW `T1` AS SELECT
aa
bb
cc
dd
FileName T2应包含: -
create statement
CREATE VIEW `T2` AS SELECT
aa
ff
ee
输出文件名来自反引号
包围的值我试过了:
sed -n '/create statement/,/create statement/p'
答案 0 :(得分:1)
Awk
解决方案:
awk '/^create statement/{ s = $0; n = NR + 1; next }
NR == n{ t = $3; gsub("`", "", t); print t ORS s > t }{ print > t }' file
结果:
$ head T[123]
==> T1 <==
T1
create statement
CREATE VIEW `T1` AS SELECT
aa
bb
cc
dd
==> T2 <==
T2
create statement
CREATE VIEW `T2` AS SELECT
aa
ff
ee
==> T3 <==
T3
create statement
CREATE VIEW `T3` AS SELECT
aa
bb
ff
答案 1 :(得分:1)
请您试着跟随并告诉我这是否对您有帮助。
awk '/create statement/{create=$0;next} /CREATE VIEW/{val=$3;gsub("`","",val);filename=val;if(create){print create ORS $0 > filename};next} {print > filename}' Input_file
它将创建3个名为T1
,T2
和T3
的输出文件,依此类推,直到T的所有出现。如果这不是您的问题,请在您的问题中明确并添加更多详细信息。
现在添加一种非单线形式的解决方案:
awk '
/create statement/{
create=$0;
next
}
/CREATE VIEW/{
val=$3;
gsub("`","",val);
filename=val;
if(create){
print create ORS $0 > filename};
next
}
{
print > filename
}
' Input_file