One way to do it using the sed editor is:
sed -e ' s/,/\n/ s/\(\n.*[[:blank:]]\)\([^,]*\),/ \2\1/ P;D ' input.file
Working:
- Clip the leading comma-separated element from the 2nd field.
- Then append this element in the 1st field's leading comma-separated element.
- Print the leading element of the 1st field and delete it after this.
- Repeat this procedure with what remains in the pattern space till it is empty.
Another method using Perl is:
perl -lane ' my($kref, $vref, %h) = map { [split /,/] } @F[0,1]; @h{@$kref} = @$vref; print "$_ $h{$_}" for @$kref; ' input.file
Another way is shown here:
perl -lpe 'print "$1 $3" while s/^([^,]*),(.*\h)([^,]*),/$2/' input.file
Working:
- Look at the regex this way: (Perl reads in a line at a time from the file) then:
- ^([^,]*) shall pick the first-field's leading comma-separated element of the current line. This is stored in $1 variable.
- (.*\h) shall preserve, for the next iteration of the while loop, the intermediate contents beginning from the second comma-separated element of the first field to the beginning of the second comma-separated element of the second field. This is stored in the $2 variable.
- ([^,]*) shall pick the leading comma-separated element from the second field of the current line.This gets stored in the $3 variable.
- Now "$1 $3" is printed out to STDOUT and the line is shrunk to $2. The while loop now performs the operation all over again on this edited line, which is $2 of the previous line,..... this repeats till the s/// succeeds. The failure comes when we run out of commas. At which point , what remains in the line, "c 5" is printed to STDOUT by the default behavior of perl in the -p mode.
- Pluck out the leading comma-separated elements from the first and second fields.
- Print those elements and also shrink the current record by removing.
- Loop over the current record while it's having 2 commas.
- Last pair is auto-printed due to the -p option of Perl.
perl -lane ' my($kref, $vref) = map { [split /,/] } @F; print shift @$kref, " ", shift @$vref while @$kref && @$vref; ' input.file
Working:
- keys are stored in an array @$kref, corresponding values in @$vref. Note no hashes involved here.
- print the top of the arrays simultaneously and then remove the top ...rinse,repeat while both the arrays are non-empty.
Output:
a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8