3

I need to transpose a file.

Input file:

1/1/1111
1
2
3
4

2/2/2222
5
6
7
8

Output:

1/1/1111 1 2 3 4
2/2/2222 5 6 7 8
don_crissti
  • 79,330
  • 30
  • 216
  • 245
dynix
  • 93
  • 1
  • 6
  • 1
    Try: http://unix.stackexchange.com/search?q=transpose –  Aug 12 '15 at 04:47
  • 1
    possible duplicate of [Transposing rows and columns](http://unix.stackexchange.com/questions/79642/transposing-rows-and-columns) –  Aug 12 '15 at 04:48
  • is it always a header line followed by 4 data lines and a blank line as separator, or is the format (e.g. the number of data lines) varying in between? – FelixJN Aug 12 '15 at 09:05

5 Answers5

4

what about xargs

 xargs -n5 < input_file

or awk

awk '{a=(NR%6==0)?"":a$0" ";if(NR%6==5)print a}' inp
FelixJN
  • 12,616
  • 2
  • 27
  • 48
Shravan Yadav
  • 224
  • 1
  • 6
3

In perl

perl -lp00e 's/\n/ /g' your_file

Explanation

  • l: Remove the input record separator from the current record being processed and add the current output record separator (a newline by default) after each printed line.
  • -p: Operate on the file record by record and print the current record after processing.
  • -00: Means the record separator is two or more consecutive newlines
  • -e : execute the following string as code while setting the default variable ($_) to the record currently being read from the file.
  • s/\n/ /g: Replace every newline encountered in the current record with a space (the g modifier ensures the replacement is "global").
Joseph R.
  • 38,849
  • 7
  • 107
  • 143
2

With sed:

$ sed -e '
  :1
  $!N
  /\n$/{
    P
    d
  }
  s/\n/ /
  t1
' <file
cuonglm
  • 150,973
  • 38
  • 327
  • 406
2

With awk:

awk '{ORS=" ";}; !NF{ORS="\n"};1' file

The ORS variable specifies the output record separator. If the number of fields is zero (the line is empty) then the record separator should be a newline, else a space. The 1 at the end just means a positive condition, so awk prints the whole line.

cuonglm
  • 150,973
  • 38
  • 327
  • 406
chaos
  • 47,463
  • 11
  • 118
  • 144
2

are they all the same format, i.e. 6 lines for each block? if so, paste is simplest (that is 6 dashes):

paste - - - - - - < file

If you need spaces rather than tabs, add -d' '

FelixJN
  • 12,616
  • 2
  • 27
  • 48