2

I have a tab-separated file like this:

211845  032
215979  002   071
217783  143   156   169
219750  111

For the lines that have multiple tab separated entries, I want to add new lines based on the value of column one. Here is my desired result:

211845  032
215979  002
215979  071
217783  143
217783  156
217783  169
219750  111

Appreciate any ideas, this one has me stumped.

1

2 Answers 2

4

With awk, loop for the fields after the first one, for every line, and print a new line for every field.

awk -F'\t' -v OFS='\t' '{for (i=2;i<=NF;i++) print $1,$i}' file

Output:

211845  032
215979  002
215979  071
217783  143
217783  156
217783  169
219750  111

This way, we discard any lines blank or having only one field, which is probably what you want. In order to keep them as they are, a modification could be:

awk -F'\t' -v OFS='\t' 'NF<2 {print; next} {for (i=2;i<=NF;i++) print $1,$i}' file
3

You can do this using GNU sed making use of its extended regex mode -E to aid in writing somewhat easy-to-read regexes.

sed -E '
  s/\t/\n/2;T
  s/^([^\t]+\t).*\n/&\1/
  P;D
' file

Outputs:

211845  032
215979  002
215979  071
217783  143
217783  156
217783  169
219750  111

  • If a line has less than 2 TABs, display it unmodified by means of the T command.
  • Display the first pair with the P command, stitch the first field at the back of the first pair.
  • This process goes on until we are left with one TAB, which then is printed by means of furst step.

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.