【问题标题】:Splitting files by 1st character - unix按第一个字符拆分文件 - unix
【发布时间】:2014-07-16 10:12:54
【问题描述】:

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

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

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

文件1:

A213 foo bar sentence
A123 bar foo sentence

文件2:

B84521 abc hello world

文件3:

C984 def word hello

我怎样才能轻松做到这一点?

【问题讨论】:

    标签: file unix split


    【解决方案1】:

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

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

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


    这个 awk 也可以做到,尽管它涉及更改字段分隔符以使其特定于字符:

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

    【讨论】:

      【解决方案2】:
      #!/usr/bin/awk -f
      { ab = substr($0,0,1);
       if(ab == "a") { printf $0"\n" >> "/dirname/file1" }
      else if(ab == "b") { printf $0"\n" >> "/dirname/file2" }
      else { printf $0"\n" >> "/dirname/file3" } }
      

      以上脚本在文件“redir”中。以redir inputfilename运行脚本

      awk 将内容拆分并重定向到单独的文件中。

      【讨论】:

        猜你喜欢
        • 2020-02-03
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 2021-06-25
        • 2017-09-08
        • 2012-05-21
        • 1970-01-01
        相关资源
        最近更新 更多