BASH - 根据条件将文件拆分成多个文件 [英] BASH - Split file into several files based on conditions

查看:108
本文介绍了BASH - 根据条件将文件拆分成多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件( input.txt ),结构如下:

 > day_1 
ABC
DEF
GHI
> day_2
JKL
MNO
PQR
> day_3
STU
VWX
YZA
> month_1
BCD
EFG
HIJ
> month_2
KLM
NOP
QRS
...

我想将该文件拆分成多个文件( day.txt ; month.txt ; ...)。每个新的文本文件都包含所有标题行(以> 开头的行)及其内容(两行标题行之间的行)。



day.txt 因此会是:

 > day_1 
ABC
DEF
GHI
> day_2
JKL
MNO
PQR
> day_3
STU
VWX
YZA

month.txt

 > month_1 
BCD
EFG
HIJ
> month_2
KLM
NOP
QRS

在这种情况下,我不能使用 split -l <​​/ code>,因为每个类别(日,月,等等。)。但是,每个子类别具有相同的行数(= 3)。

根据OP,现在再添加1个解决方案。

  awk -F'[> _]''/^>/{file=$2\".txt} {打印> file}'Input_file 

解释:

  awk -F'[> _]''##创建字段分隔符为>或_在当前行中。 
/ ^> / {file = $ 2.txt} ##搜索以>开头的行如果是,则创建一个名为file的变量,其值为第二个字段.txt
{print>文件} ##打印当前行到变量文件(这将创建变量文件的值的文件名)。
'Input_file ##在这里提到Input_file的名字。

awk 可以帮助你。

  awk'/^> ;day/{file=\"day.txt} / ^>月/ {file = month.txt} {print> file}'Input_file 


I have a file (input.txt) with the following structure:

>day_1
ABC
DEF
GHI
>day_2
JKL
MNO
PQR
>day_3
STU
VWX
YZA
>month_1
BCD
EFG
HIJ
>month_2
KLM
NOP
QRS
...

I would like to split this file into multiple files (day.txt; month.txt; ...). Each new text file would contain all "header" lines (the one starting with >) and their content (lines between two header lines).

day.txt would therefore be:

>day_1
ABC
DEF
GHI
>day_2
JKL
MNO
PQR
>day_3
STU
VWX
YZA

and month.txt:

>month_1
BCD
EFG
HIJ
>month_2
KLM
NOP
QRS

I cannot use split -l in this case because the amount of lines is not the same for each category (day, month, etc.). However, each sub-category has the same number of lines (=3).

解决方案

EDIT: As per OP adding 1 more solution now.

awk -F'[>_]' '/^>/{file=$2".txt"} {print > file}'  Input_file

Explanation:

awk -F'[>_]' '        ##Creating field separator as > or _ in current lines.
/^>/{ file=$2".txt" } ##Searching a line which starts with > if yes then creating a variable named file whose value is 2nd field".txt"
    { print > file  } ##Printing current line to variable file(which will create file name of variable file's value).
'  Input_file         ##Mentioning Input_file name here.

Following awk may help you on same.

awk '/^>day/{file="day.txt"} /^>month/{file="month.txt"} {print > file}' Input_file

这篇关于BASH - 根据条件将文件拆分成多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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