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

后端 未结 4 1302
眼角桃花
眼角桃花 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<NF&&i%2?FS:RS.

    0 讨论(0)
  • 2020-12-11 10:00

    Can't add comment to wintermutes answer but it doesn't need the first , section as it will have to have had a previous field to be comma separated.

    sed 's/\(,[^,]*\),/\1\n/g'
    

    Will work the same

    Also I'll add another alternative( albeit worse and leaves a trailing newline)

    echo "1,2,3,4,5,6,7,8,9,10" | xargs -d"," -n2 | tr ' ' ','
    
    0 讨论(0)
  • 2020-12-11 10:01

    This might work for you (GNU sed):

    sed 's/,/\n/2;P;D' file
    
    0 讨论(0)
  • 2020-12-11 10:06

    If I understand what you're trying to do correctly, then

    echo '1,2,3,4,5,6,7,8,9,10' | sed 's/\([^,]*,[^,]*\),/\1\n/g'
    

    seems like the most straightforward way. \([^,]*,[^,]*\) will capture 1,2, 3,4, and so forth, and the commas between them are replaced with newlines through the usual s///g. This will print

    1,2
    3,4
    5,6
    7,8
    9,10
    
    0 讨论(0)
提交回复
热议问题