按第一个字符分割文件-UNIX [英] Splitting files by 1st character - unix

查看:57
本文介绍了按第一个字符分割文件-UNIX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的文件(假设文件已排序):

I have a file as such (assume that file is sorted):

A213 foo bar sentence
A123 bar foo sentence
B84521 abc hello world
C984 def word hello

我需要根据每行的第一个字符将其分为三个文件:

I need to split it up into three files based on the 1st character of each line:

文件1:

A213 foo bar sentence
A123 bar foo sentence

文件2:

B84521 abc hello world

文件3:

C984 def word hello

我如何轻松地做到这一点?

How can I do that easily?

推荐答案

您可以使用以下 awk 将所有行重定向到特定的文件名:

You can use this awk to redirect all lines to an specific file name:

awk '{print > substr($0, 1, 1)}' file

因为 substr($ 0,1,1)返回该行的第一个字符,而 print> 将输出重定向到给定的文件名.(请注意:它从1开始,而不是0,正如Ed Morton在评论中指出的那样.)

Because substr($0, 1, 1) returns the first character of the line and print > redirects the output to the given file name. (Note: it starts at 1, not 0, as noted by Ed Morton in comments.)

虽然它涉及到更改字段分隔符以使其特定于字符,但它还是由awk实现的:

Also this awk makes it, although it involves changing the field separator to make it character specific:

awk -v FS= '{print > $1}' file

这篇关于按第一个字符分割文件-UNIX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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