[英]Linux script: how to split a text into different files with match pattern
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
{if ($0 ~ /start/) a++}
looks for lines containing the word start
. {if ($0 ~ /start/) a++}
查找包含单词start
。 If so, increments the variable a
, which is 0
by default. a
递增,默认情况下为0
。 {print >> "file"}'
prints $0
(that is, the whole line) to a file called "file" in the same directory. {print >> "file"}'
$0
(即整行)打印到同一目录中名为“ file”的文件中。 {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
... {print >> "file"a}
将行打印到名为“ file” +变量a
文件,该文件恰好是0、1、2 ...,因此将其打印到file1
, file2
... $ 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
对于awk,“ if($ 0〜)”是隐式的。
awk 'BEGIN{a=0;b=0} /start/{a++;b=1} (b==1){print >> "file"a} /stop/{b=0}' input_file.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.