Reputation: 15
I have this string stored in a file :
ID1,A,B,,,,F
ID2,,,,D,E,F
ID3,,B,C,,,,
and I need to transform like this :
ID1,A
ID1,B
ID1,F
ID2,D
ID2,E
...
I tried with loop and IFS (like IFS=","; declare -a Array=($*)) whitout success.
Does someone knows how to do that ?
Upvotes: 1
Views: 122
Reputation: 5298
awk -F, '{for (i=2; i<=NF; i++) if($i != "") print $1","$i}' File
ID1,A
ID1,B
ID1,F
ID2,D
ID2,E
ID2,F
ID3,B
ID3,C
With ,
as the field seperator, for each line, loop from the 2nd
field to the last
field. If the current field
is not empty, print the first field
(IDx
) and the current field
seperated by a ,
Upvotes: 1
Reputation: 85590
Pretty straight-forward in Awk,
awk 'BEGIN{FS=OFS=","}{first=$1; for (i=2;i<=NF;i++) if (length($i)) print first,$i}' file
Setting input and output field separator to ,
store the first field separately in first
variable and print rest of the non-empty fields.
As suggested by user @PS. below you can also do,
awk -F, '{for(i=2;i<=NF;i++) if(length($i)) print $1 FS $i}' file
Upvotes: 2