Tuesday, November 24, 2009

Expand entries in file using awk - bash


Input file:

$ cat data.txt
Manager3|sw5
Manager2|sw engg9,sw12
Manager1|sw1,sw4,sw2,sw engg0

Output required:

Manager3|sw5
Manager2|sw engg9
Manager2|sw12
Manager1|sw1
Manager1|sw4
Manager1|sw2
Manager1|sw engg0

I have already posted (using awk and another using python) the reverse solution of the above, i.e. converting the above expected output to the input file format.

Awk solution:

$ awk -F "|" '{
n=split($2,Arr,",")
for(i=1; i<=n;i++){printf "%s|%s\n",$1,Arr[i]}}
' data.txt

3 comments:

Mahesh Kharvi said...

awk -F"|" '{gsub(",","\n"$1"|");print}'

Jadu Saikia said...

@Mahesh, such a short and good one, I never thought of this. Thanks

Mahesh Kharvi said...

Thanks jadu :-)

© Jadu Saikia www.UNIXCL.com