【问题标题】:Split file based on string delimiter in bash.how? [duplicate]基于bash.how中的字符串分隔符拆分文件? [复制]
【发布时间】:2010-12-21 23:55:07
【问题描述】:

我有这个文件.csv:

coordinate1,coordinate2,value1
11111,a1,65
11111,a2,32
22222,b1,39
22222,b3,55
33333,c5,12
33333,c9,16
coordinate1,coordinate2,value2
54656,a1,65
21342,a2,32
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
568568,c5,12
568568,c9,16
coordinate1,coordinate2,value3
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
11111,a1,65
11111,a2,32
22222,b1,39
22222,b3,55
33333,c5,12
33333,c9,16

现在我想把这个文件分成 3 个文件,每个人都只有一个数据块

Es: 1° file
   coordinate1,coordinate2,value1
    11111,a1,65
    11111,a2,32
    22222,b1,39
    22222,b3,55
    33333,c5,12
    33333,c9,16

Es: 2° file
    coordinate1,coordinate2,value2
    54656,a1,65
    21342,a2,32
    23543,b1,39
    123123,b3,55
    568568,c5,12
    568568,c9,16
    123123,b3,55
    568568,c5,12
    568568,c9,16

【问题讨论】:

    标签: bash file split


    【解决方案1】:

    公然从this forum盗取:

    awk '/YOUR_TEXT_HERE/{n++}{print >"out" n ".txt" }' final.txt
    

    应该可以解决问题(当然,替换 YOUR_TEXT_HERE)。

    用您的条件替换它,并将输出发送到#file.txt,输入文件为a.txt

    $ awk '/coordinate1,coordinate2,value?/{n++}{print > n "file.txt" }' a.txt $ ls 1file.txt 2file.txt 3file.txt a.txt $ 猫 1file.txt 坐标1,坐标2,值1 11111,a1,65 11111,a2,32 22222,b1,39 22222,b3,55 33333,c5,12 33333,c9,16 $ 猫 2file.txt 坐标1,坐标2,值2 54656,a1,65 21342,a2,32 23543,b1,39 123123,b3,55 568568,c5,12 568568,c9,16 123123,b3,55 568568,c5,12 568568,c9,16 $ 猫 3file.txt 坐标1,坐标2,值3 23543,b1,39 123123,b3,55 568568,c5,12 568568,c9,16 123123,b3,55 23543,b1,39 123123,b3,55 568568,c5,12 568568,c9,16 123123,b3,55 11111,a1,65 11111,a2,32 22222,b1,39 22222,b3,55 33333,c5,12 33333,c9,16

    【讨论】:

    • 我试过这个例子。我收到以下错误:awk: 在源代码行 1 上下文的语法错误是 /coordinate1,coordinate2,value?/{n++}{print > n >>> "file.txt"
    • @RaffiKhatchadourian 您使用的是哪个版本的 awk?
    • @Armali awk 版本 20070501
    • 如果我想将文件拆分成包含 x-times 标头(或某种模式)的块怎么办?
    • 是否可以根据? 来命名输出文件? (例如,123 在此示例中)
    【解决方案2】:

    另一个答案的不同引用版本也适用于 Windows CMD:

    awk "/coordinate1,coordinate2,value?/{n++}{print>n\"file.txt\"}" a.txt
    

    【讨论】:

      【解决方案3】:

      你可以使用 csplit:

      csplit file.txt /^c.*/ {*}
      

      此语法在 cygwin 上有效,但在其他地方没有尝试过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-08
        • 2015-06-26
        • 2011-11-28
        • 2014-03-13
        • 2021-12-17
        • 2012-02-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多