5

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?

12

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.)

5

With GNU sed:

sed -E 's/^((\S+\s+)\S+)\s+/&\n\2/;P;D'

It's just uglier with POSIX sed syntax:

s='[[:space:]]\{1,\}' S='[^[:space:]]\{1,\}'
sed "s/^\(\($S$s\)$S\)$s/&\\
\2/;P;D"
2

another awk one:

~$>echo '1   the mouse is dead
2   hit the wall
3   winter lasts forever
' | awk 'BEGIN { RS="[[:space:]]+"; } /^[[:digit:]]+$/ {line=$1; next}; { print line "\t" $1; }'
1   the
1   mouse
1   is
1   dead
2   hit
2   the
2   wall
3   winter
3   lasts
3   forever

and laid out slightly better..

# split all parts into single word records.
BEGIN { RS="[[:space:]]+"; } 

# if the record is a number the save
/^[[:digit:]]+$/ { line=$1; next }; 
# else use last saved line number and this record to format output.
{ print line "\t" $1; }
1

You can also use the split function with awk:

awk -F"\t" 'BEGIN { OFS="\t" } { cols=split($2,arr," "); for ( i=1; i<=cols; i++ ) { print $1,arr[i] }}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.