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
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
.
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 ' ' ','
This might work for you (GNU sed):
sed 's/,/\n/2;P;D' file
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