Linux 脚本:如何使用匹配模式将文本拆分为不同的文件 [英] Linux script: how to split a text into different files with match pattern

查看:37
本文介绍了Linux 脚本:如何使用匹配模式将文本拆分为不同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:我有一段文字如下:

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

我该怎么做?谢谢.

推荐答案

这可以做到:

$ awk '{if ($0 ~ /start/) a++} {print >> "file"a}' file

说明

  • {if ($0 ~/start/) a++} 查找包含单词 start 的行.如果是,则增加变量 a,默认为 0.
  • {print >>"file"}'$0(即整行)打印到同一目录中名为file"的文件中.
  • {print >>"file"a} 将该行打印到一个名为 "file" + 变量 a 的文件中,该文件恰好是 0, 1, 2 ... 所以它打印到 file1, file2...
  • 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...
    • $ 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
      

      这篇关于Linux 脚本:如何使用匹配模式将文本拆分为不同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆