按第一个字符分割文件-UNIX

alv*_*vas 1 unix split file

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

A213 foo bar sentence
A123 bar foo sentence
B84521 abc hello world
C984 def word hello
Run Code Online (Sandbox Code Playgroud)

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

文件1:

A213 foo bar sentence
A123 bar foo sentence
Run Code Online (Sandbox Code Playgroud)

文件2:

B84521 abc hello world
Run Code Online (Sandbox Code Playgroud)

文件3:

C984 def word hello
Run Code Online (Sandbox Code Playgroud)

我如何轻松做到这一点?

fed*_*qui 5

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

awk '{print > substr($0, 1, 1)}' file
Run Code Online (Sandbox Code Playgroud)

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


尽管它涉及到更改字段分隔符以使其特定于字符,但该awk还是可以做到的:

awk -v FS= '{print > $1}' file
Run Code Online (Sandbox Code Playgroud)