Linux script: how to split a text into different f

2019-08-30 01:29发布

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.

2条回答
神经病院院长
2楼-- · 2019-08-30 02:24

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
查看更多
走好不送
3楼-- · 2019-08-30 02:24

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
查看更多
登录 后发表回答