Breaking a column's value into multiple rows

Hello Friends,

I am trying to implement the following using UNIX. I am getting a sequential file as input which would have two columns, "Name" and "Countries Visited". The "Countries Visisted" field will be multi-valued, each value separated by a space and also the number of values are not fixed. The file is tab delimited.
For example,
Name Countries Visited
A US UK CA
B US HT UG CA IN
C US
D CN PA
My intended output is this:
Name Countries Visited
A US
A UK
A CA
B US
B HT
B UG
B CA
B IN
C US
D CN
D PA
How can I use UNIX Shell Scripting to do this?
Many Thanks!!

regards

Easy solution in awk:

#!/usr/bin/env ksh
awk '
        NF > 1 {
                for( i = 2; i <= NF; i++ )
                        printf( "%s %s\n", $1, $(i) );
        }
' <input_file

Strictly using shell commands:

while read name list
do
    for c in $list
    do
        echo "$name $c"
    done
done <input file
1 Like
awk 'NR==1{print;next} {for (i=2;i<=NF;i++)print $1,$i}' infile
1 Like