1

I have the following list in file

more file.ex

efifc1a
hygg4a
hdy5d


nhdw4s
wesf3a
fjfhyr



jfhg
gsfar

how to append any second list after the first list and any third list after the second list the following:

efifc1a   nhdw4s     jfhg
hygg4a    wesf3a     gsfar
hdy5d     fjfhyr
yael
  • 1,521

2 Answers2

2

How about

awk '
  BEGIN {FS="\n"; RS="\n\n+"}
  {for (i=1;i<=NF;i++) a[i] = a[i] == ""? $i : a[i]"\t"$i; next}
  END {for (i in a) print a[i]}
' file.ex

Testing:

awk '
>   BEGIN {FS="\n"; RS="\n\n+"}
>   {for (i=1;i<=NF;i++) a[i] = a[i] == ""? $i : a[i]"\t"$i; next}
>   END {for (i in a) print a[i]}
> ' file.ex
efifc1a nhdw4s  jfhg
hygg4a  wesf3a  gsfar
hdy5d   fjfhyr  

If you're not stuck on using awk, you could do it using autogen's columns command and the transpose command described here Transposing rows and columns e.g.

columns -c3 < file.ex | tr -s ' ' '\t' | transpose -t
steeldriver
  • 81,074
  • Standard awk iterates for (i in a) in indeterminate order; for the gawk's I have numbers up to 3 (your test case) happen to work but more don't; oh Ubuntu mawk up to 9 works, but on FreeBSD awk even 2 fails, and I no longer have Solaris. Recent GNU awk can fix this with PROCINFO["sorted_in"] but anywhere and easier you can use for(i = 1; i in a; i++) print a[i]. – dave_thompson_085 May 18 '16 at 00:29
  • @dave_thompson_085 good info, thanks – steeldriver May 18 '16 at 00:48
1

If you accept having temporary files, you could do it as a two step process with awk and paste:

n=$(awk '{ print $0 > NR; close(NR) } END { print NR }' RS= file.ex)
paste $(seq $n)

Or as a one-liner:

paste $(seq $(awk '{ print $0 > NR; close(NR) } END { print NR }' RS= file.ex))

Output in both cases:

efifc1a nhdw4s  jfhg
hygg4a  wesf3a  gsfar
hdy5d   fjfhyr  

Note, this creates numbered files in the current directory, so take care not to overwrite other files.

Thor
  • 17,182