提取数据并保存在不同的输出文件中 [英] Extract data and save in different output files

查看:65
本文介绍了提取数据并保存在不同的输出文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下格式的数据文件:

I have a data file with the following format:

aaa     0
bbb     1
ccc     2
ddd     ?
eee     0
fff     1
ggg     2
hhh     3
iii     ?
   ...

我想做的事情很简单:提取数据的一部分并将其保存在不同的文件中,并且拆分的条件是仅取0到'?之间的行.这样我就可以获得:

What I want to do is quite simple: extract and save the parts of the data in different files with the criteria for splitting being only taking the lines between 0 and the '?' so that I would obtain:

output_1.txt>

output_1.txt >

aaa     0
bbb     1
ccc     2
ddd     ?

output_2.txt>

output_2.txt >

eee     0
fff     1
ggg     2
hhh     3
iii     ?

依次类推,直到到达输入文件的末尾. 我尝试研究awk命令,但是我不确定如何指定条件,也不确定如何创建取决于数据拆分次数的输出文件.

And so on until the end of the input file is reached. I've tried to look into awk command but I'm not quite sure how to specify the conditions nor how to create an output file that depends on the number of times the data is split.

推荐答案

您需要的是:

awk 'NR==1 || $NF=="?"{close(out); out="output_"++cnt".txt"} {print > out}' file

以上内容适用于任何大小的输入文件的任何UNIX系统上任何shell中的任何awk.

The above will work with any awk in any shell on any UNIX system for any size of input file.

如果您想对?进行部分匹配(请参见下面的评论),则可以选择以下任一选项:

If you wanted to do a partial match on ? (see the comments below) then it'd be either of these:

awk 'NR==1 || index($NF,"?"){close(out); out="output_"++cnt".txt"} {print > out}' file

awk 'NR==1 || $NF~/\?/{close(out); out="output_"++cnt".txt"} {print > out}' file

awk 'NR==1 || $NF~/[?]/{close(out); out="output_"++cnt".txt"} {print > out}' file

这篇关于提取数据并保存在不同的输出文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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