Sunday, 15 November 2015

How to Convert Single Row in Multiple Rows using AWK

Input file :F_Data_File.txt

V1|a1
V2|b1,b2,b3
V3|e1,e2,e3,e4
V4|d1,d2

Desired Output:

V1|a1
V2|b1
V2|b2
V2|b3
V3|e1
V3|e2
V3|e3
V3|e4
V4|d1
V4|d2

Solution:

$ awk -F "|" '{
               V_Split=split($2,V_Arr,",")
               for(i=1; i<=V_Split;i++)
              {
                print ($1,V_Arr[i])
              }
             }' F_Data_File.txt

Explanation:

1. SPLIT function will split the second column of input data into array V_Arr based on comma(,).
2. V_Split will hold  COUNT of attributes available in array V_Arr.
3. When awk will read first row V_Split will hold value as 1, for second row 3, for third row 4 and it will hold 2 for 4th row.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...