CodeDevotion
CodeDevotion

Reputation: 307

Convert comma separated values to rows using AWK but starting from second column

I am working on below sample.txt file to convert the columns to rows but starting from second column.

$ cat sample.txt
ENGLISH,UK,USA,CA,SA
HINDI,IN,NEP
SPANISH,MEX,SPAIN,AG
FRENCH,FR,CA

Looking for following output.

1,ENGLISH,UK
2,ENGLISH,USA
3,ENGLISH,CA
4,ENGLISH,SA
1,HINDI,IN
2,HINDI,NEP
1,SPANISH,MEX
2,SPANISH,SPAIN
3,SPANISH,AG
1,FRENCH,FR
2,FRENCH,CA

This is what I could achieve so far..

$ cat sample.txt | awk -F',' '{out=$1; for(i=2;i<=NF;i++){out=(i-1)" "$1" "$i}; print out}'
4 ENGLISH SA
2 HINDI NEP
3 SPANISH AG
2 FRENCH CA

Upvotes: 3

Views: 355

Answers (2)

vk239
vk239

Reputation: 1044

Move the print statement inside for loop. Your code should look like below:

$ cat sample.txt | awk -F',' '{out=$1; for(i=2;i<=NF;i++){out=(i-1)","$1","$i; print out;}}' 

Output:

1,ENGLISH,UK
2,ENGLISH,USA
3,ENGLISH,CA
4,ENGLISH,SA
1,HINDI,IN
2,HINDI,NEP
1,SPANISH,MEX
2,SPANISH,SPAIN
3,SPANISH,AG
1,FRENCH,FR
2,FRENCH,CA

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203209

$ awk 'BEGIN{FS=OFS=","} {for (i=2;i<=NF;i++) print i-1, $1, $i}' sample.txt
1,ENGLISH,UK
2,ENGLISH,USA
3,ENGLISH,CA
4,ENGLISH,SA
1,HINDI,IN
2,HINDI,NEP
1,SPANISH,MEX
2,SPANISH,SPAIN
3,SPANISH,AG
1,FRENCH,FR
2,FRENCH,CA

Mainly you were just overwriting "out" every iteration through the loop.

Upvotes: 4

Related Questions