Linux script: how to split a text into different f

2019-08-30 01:54发布

问题:

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.

回答1:

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


回答2:

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