Separate the element after every 2nd ',' and push into next row in bash
Using a Sed loop:
sed -e 's/,/\n/2' -e 'P;D' file
Ex.
$ echo '201012,720,201011,119,201710,16' | sed -e 's/,/\n/2' -e 'P;D'
201012,720
201011,119
201710,16
This replaces the second ,
with \n
, then prints and deletes up the \n
, repeatedly until the substitution is no longer successful.
BSD doesn't understand newline as \n
in right side of s
commands, this is a workaround for ksh,bash,zsh shells:
sed -e :a -e $'s/,/\\\n/2' -e 'P;D' file
Or, a general solution for (old) seds:
sed '
:a
s/,/\
/2
P;D
' file
$ paste -d, - - < <( tr ',' '\n' <file )
201012,720
201011,119
201710,16
or, without the process substitution,
$ tr ',' '\n' <file | paste -d, - -
201012,720
201011,119
201710,16
This replaces all commas in the file with newlines using tr
, then uses paste
to create two columns separated by a comma from that.
If tr
feels a bit too simple, you may replace it with sed 'y/,/\n/'
, which does the same thing.
I was able to accomplish this with the following awk command:
awk -F, -v OFS=, '{for (i=1;i<=NF;i=i+2) {j=i+1; print $i,$j}}' input
This will loop through each column in the input (incrementing by 2 each iteration) and print that column plus the next adjacent column on a line before moving to the next.
$ cat input
201012,720,201011,119,201710,16
$ awk -F, -v OFS=, '{for (i=1;i<=NF;i=i+2) {j=i+1; print $i,$j}}' input
201012,720
201011,119
201710,16