Text Processing – How to Split File Lines Based on First Field

awklinuxsedtext processing

I have file with content like below and want to convert my output like below

  • Input

    1,a,b,c
    2,b,c
    3,e,f
    4,l
    
  • Required output

    1,a
    1,b
    1,c
    2,b
    2,c
    3,e
    3,f
    4,l
    

Values on first field is unique and no duplicate lines for 1st field in the input.

I am new to scripting and not sure how can we do this.

Best Answer

You can use awk and loop through the fields starting with 2:

awk -F, '{ OFS=FS; for (i=2;i<=NF;i++) print $1,$i }' file

Output:

1,a
1,b
1,c
2,b
2,c
3,e
3,f
4,l
Related Question