Reputation: 640
I am having data in below format and I am trying to capture data between 2 occurrence of string and keep it in a file.
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
..
...
..
I want output in below format :
FileName T1 should contain :--
create statement
CREATE VIEW `T1` AS SELECT
aa
bb
cc
dd
FileName T2 should contain :--
create statement
CREATE VIEW `T2` AS SELECT
aa
ff
ee
Output filename comes from the value surrounded by backticks
I tried:
sed -n '/create statement/,/create statement/p'
Upvotes: 0
Views: 76
Reputation: 23667
With GNU awk
awk -F'`' -v ORS= -v RS='create' 'NF{print RS $0 > $2}' ip.txt
-F'`'
use backtick as input field separator-v ORS=
empty ORS to avoid extra new line-v RS='create'
use create
as input record separatorNF{print RS $0 > $2}
for non-empty records, print value of RS and input record to file with second field as filename (which will be T1, T2, etc)Upvotes: 0
Reputation: 133458
Could you please try following and let me know if this helps you.
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
It will create 3 output files named T1
, T2
and T3
and so on till all the occurrences of T's. If this is not your question then please be clear in your question and add more details on it too.
Adding a non-one liner form of solution too now:
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
Upvotes: 1
Reputation: 92854
Awk
solution:
awk '/^create statement/{ s = $0; n = NR + 1; next }
NR == n{ t = $3; gsub("`", "", t); print t ORS s > t }{ print > t }' file
Results:
$ 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
Upvotes: 1