开发者

Unix - Split line after 9th comma

I writing a ksh shell scr开发者_StackOverflow中文版ipt and I have long comma separated string that I need to divide into separate lines only after the 9th comma. After the 9th comma, I want to remove that comma and make a new line:

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

Output:

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

I know this is possible with awk but I am not so familiar with command. Can someone please provide how to do this

Thanks


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

Note: useless use of cat for clarity: this could be any process

Depending on your actual need, drop the sed step and get the output space delimited

Bonus points:

Input (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

Output

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

If you want homogeneous line-filling, add paste:

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


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

Explanation: NF is the number of fields. $i is the i'th field; the $ is an operator in Awk, not a sigil.


$ 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜