Replace every n'th occurrence in huge line in a loop

后端 未结 4 1308
眼角桃花
眼角桃花 2020-12-11 09:55

I have this line for example:

1,2,3,4,5,6,7,8,9,10

I want to insert a newline (\\n) every 2nd occurrence of \",\" (replace the 2nd, with ne

4条回答
  •  庸人自扰
    2020-12-11 09:58

    I would use awk to do this:

    $ awk -F, '{ for (i=1; i<=NF; ++i) printf "%s%s", $i, (i%2?FS:RS) }' file
    1,2
    3,4
    5,6
    7,8
    9,10
    

    It loops through each field, printing each one followed by either the field separator (defined as a comma) or the record separator (a newline) depending on the value of i%2.

    It's slightly longer than the sed versions presented by others, although one nice thing about it is that you can alter the number of columns per line easily by changing the 2 to whatever value you like.

    To avoid a trailing comma after the last field in the case where the number of fields isn't evenly divisible, you can change the ternary to i.

提交回复
热议问题