在AWK使用的第一个字段作为文件名 [英] Using the first field in AWK as file name

查看:125
本文介绍了在AWK使用的第一个字段作为文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该数据集是一个大文件有三列:一节,一些无关紧要的文本行的ID。一个例子可能看起来像下面这样:

  A01 001这是一个简单的测试。
A01 002只是为了示范性的目的。
A01 003
A02 001这是另一个文本

我要使用的第一列(在本实施例A01和A02,从而重新present不同文本)是文件名,伟驰内容是一切在该行的第二列之后

上面的例子应该产生两个文件,​​一个名称为 A01 和内容:

 这是一个简单的测试。
只是示范性的目的。

和另一个 A02 与内容:

 这是另一个文本

我的问题是:


  1. AWK是该任务的合适的计划?或者,也许有更多的方便易办法这样做呢?

  2. 怎么会这个任务完成?


解决方案

AWK 非常适合这类任务。如果你不介意有一些前导空格,你可以使用:

 的awk'{F = $ 1; $ 1 = $ 2 =;打印> F}'文件

这将清空第一和第二场,然后打印所有行成˚F文件,该文件是pviously存储为第一场$ P $。

而在情况下,这些空间打扰,你可以用删除子(,)

 的awk'{F = $ 1; $ 1 = $ 2 =;子(,);打印> F}'文件

The dataset is one big file with three columns: An ID of a section, something irrelevant and a line of text. An example could look like the following:

A01 001 This is a simple test.
A01 002 Just for exemplary purpose.
A01 003
A02 001 This is another text

I want to use the first column (in this example A01 and A02, which represent different texts) to be the file name, whichs content is everything in that line after the second column.

The example above should result two files, one with name A01 and content:

This is a simple test.
Just for exemplary purpose.

and another one A02 with content:

This is another text

My questions are:

  1. Is AWK the appropriate program for this task? Or perhaps there are more convinient ways doing this?
  2. How would this task be done?

解决方案

awk is perfect for these kind of tasks. If you do not mind to have some leading spaces, you can use:

awk '{f=$1; $1=$2=""; print > f}' file

This will empty first and second fields and then print all the line into the f file, which was previously stored as first field.

And in case these spaces are bothering, you can delete them with sub(" ", ""):

awk '{f=$1; $1=$2=""; sub("  ", ""); print > f}' file

这篇关于在AWK使用的第一个字段作为文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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