Unix - 第9个逗号后的分割线

时间:2011-07-15 14:29:07

标签: unix shell awk ksh

我写了一个ksh shell脚本,我有一个长逗号分隔的字符串,我需要在第9个逗号之后分成单独的行。在第9个逗号之后,我想删除该逗号并创建一个新行:

例如: 初始字符串 1,2,3,4,5,6,7,8,9,10,11,12,13,14,14,15,16,17,18,19,20,21

输出:

1,2,3,4,5,6,7,8,9,10
11,12,13,14,14,15,16,17,18,19,20
21

我知道awk可以实现这一点,但我对命令并不熟悉。有人可以提供如何做到这一点

由于

3 个答案:

答案 0 :(得分:3)

awk -F, '{
    for (i=1; i<=NF; i++) {
        printf("%s", $i);
        if (i % 10 == 0 || i == NF)
            printf "\n";
        else
            printf ",";
    }
}' textfile

说明:NF是字段数。 $ii'字段; $是Awk中的运算符,而不是sigil

答案 1 :(得分:3)

cat t.txt | xargs -d, -rn10 | sed 's/ /,/g'

注意:为了清楚起见,无用cat:这可能是任何过程

根据您的实际需要,删除sed步并获取输出空格分隔

奖励积分:

输入(t.txt)

1,2,3,4,5,6,7,8,9,10,11,12,13,14,14,15,16,17,18,19,20,21
22,23
24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50

输出

1,2,3,4,5,6,7,8,9,10
11,12,13,14,14,15,16,17,18,19
20,21
22,23
24,25,26,27,28,29,30,31
32,33,34,35,36,37,38,39,40,41
42,43,44,45,46,47,48,49,50

如果您想要均匀填充线条,请添加粘贴:

  

<强> paste -sd, t.txt | xargs -d, -n10 | sed 's/ /,/g'

1,2,3,4,5,6,7,8,9,10
11,12,13,14,14,15,16,17,18,19
20,21,22,23,24,25,26,27,28,29
30,31,32,33,34,35,36,37,38,39
40,41,42,43,44,45,46,47,48,49
50

答案 2 :(得分:2)

$ s='1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21'

$ print "$s" | tr , '\n' | paste -d , - - - - - - - - - - | sed -e 's/,\+$//'
1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20
21

$ print "$s" | tr , '\n' | xargs -n 10 echo | tr " " ,
1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20
21