For example:
I have a text as following:
Jul 11 xxxx xxxx start xxxxx
....
....
....
Jul 11 xxxx xxxx stop xxxxx
Jul 11 xxxx xxxx start xxxxx
....
....
....
Jul 11 xxxx xxxx stop xxxxx
....
now I want to split the above text file into different files based on "start" and "stop", like
/***text1.txt******/
Jul 11 xxxx xxxx start xxxxx
....
....
....
Jul 11 xxxx xxxx stop xxxxx
/***text2.txt******/
Jul 11 xxxx xxxx start xxxxx
....
....
....
Jul 11 xxxx xxxx stop xxxxx
How can I do that? Thanks.
This can make it:
$ awk '{if ($0 ~ /start/) a++} {print >> "file"a}' file
Explanation
{if ($0 ~ /start/) a++}
looks for lines containing the word start
. If so, increments the variable a
, which is 0
by default.
{print >> "file"}'
prints $0
(that is, the whole line) to a file called "file" in the same directory.
{print >> "file"a}
prints the line to a file called "file" + variable a
, which happens to be 0, 1, 2... So it prints to file1
, file2
...
Test
$ cat a
Jul 11 xxxx xxxx start xxxxx
....
....
....
Jul 11 xxxx xxxx stop xxxxx
Jul 11 xxxx xxxx start xxxxx
here begins 2nd file
....
....
....
Jul 11 xxxx xxxx stop xxxxx
$ awk '{if ($0 ~ /start/) {a++}} {print >> "file"a}' a
$ cat file1
Jul 11 xxxx xxxx start xxxxx
....
....
....
Jul 11 xxxx xxxx stop xxxxx
$ cat file2
Jul 11 xxxx xxxx start xxxxx
here begins 2nd file
....
....
....
Jul 11 xxxx xxxx stop xxxxx
With awk, 'if ($0 ~ )' is implicit.
awk 'BEGIN{a=0;b=0} /start/{a++;b=1} (b==1){print >> "file"a} /stop/{b=0}' input_file.txt