Lum – How to split field 1 into distinct rows but keep field 2 copied for each new row created

awkcolumnstext processing

Input:

Note: 2 columns separated by a tab, regular spaces separating words in column 2.

1   the mouse is dead
2   hit the wall
3   winter lasts forever

Wanted output:

1   the
1   mouse
1   is
1   dead
2   hit
2   the
2   wall
3   winter
3   lasts
3   forever

Is awk the way to go for this?

Best Answer

Well, the first field is $1, NF holds the number of fields on the line, we can access the fields with $i where i is a variable, and loops work almost like in C. So:

$ awk '{for (i = 2; i <= NF; i++) printf "%s\t%s\n", $1, $i} ' < blah
1       the
1       mouse
...

(This doesn't differentiate between space and tab as field separator.)

Related Question