Aires69
Aires69

Reputation: 87

get entries within a paragraph using sed or awk

I've a file as follows:

[para1]
abc-1-10 interpreter=/bin/sed
abc-1-11 interpreter=/bin/sed
[para2]
abc-2-100 interpreter=/bin/sed
abc-2-205 interpreter=/bin/sed
abc-2-206 interpreter=/bin/sed
[para3]
abc-3-15 interpreter=/bin/sed
abc-3-18 interpreter=/bin/sed

I need each para written to a separate file i.e. the line [para1] and the two entries i.e. abc-1-10 and abc-1-11

I tried

awk -v Var="\[para" '$1~Var{p=1}/^$/{p=0}p /tmp/filename 

which gives an error as: awk:warning: escape sequence '\[' treated as plain '['

I also tried awk -v Var="para" '$1~Var{p=1}/^$/{p=0}p /tmp/filename and it prints the whole file!!. Any help is much appreciated.

Upvotes: 0

Views: 43

Answers (2)

potong
potong

Reputation: 58473

This might work for you (GNU csplit):

csplit -q -f file -b %d.txt inputFile '/^\[/' '{*}' && rm file0.txt

Quiet, prefix of file, suffix of n.txt and remove the first empty file.

Upvotes: 0

sseLtaH
sseLtaH

Reputation: 11237

Using awk

$ awk '/^\[para/ {close(para);para="file"++c".txt"}{print > para}' input_file
$ head file*.txt
==> file1.txt <==
[para1]
abc-1-10 interpreter=/bin/sed
abc-1-11 interpreter=/bin/sed

==> file2.txt <==
[para2]
abc-2-100 interpreter=/bin/sed
abc-2-205 interpreter=/bin/sed
abc-2-206 interpreter=/bin/sed

==> file3.txt <==
[para3]
abc-3-15 interpreter=/bin/sed
abc-3-18 interpreter=/bin/sed

Upvotes: 1

Related Questions