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
3

5 Answers 5

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").
1
  • 1
    perl -lp00e 's/\n/ /g' is shorter and work with old perl.
    – cuonglm
    Aug 12, 2015 at 6:03
3

what about xargs

 xargs -n5 < input_file

or awk

awk '{a=(NR%6==0)?"":a$0" ";if(NR%6==5)print a}' inp
2
  • Both methods assume a fixed number of entries per "column" which the OP doesn't explicitly specify.
    – Joseph R.
    Aug 12, 2015 at 6:16
  • yes right. Still working on that. Aug 12, 2015 at 6:20
2

With sed:

$ sed -e '
  :1
  $!N
  /\n$/{
    P
    d
  }
  s/\n/ /
  t1
' <file
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' '

1

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.

2
  • This will remove the last newline of file, and also doesn't work if line contain 0.
    – cuonglm
    Aug 12, 2015 at 5:51
  • @cuonglm Thanks for the note, now it works also with a 0.
    – chaos
    Aug 12, 2015 at 6:02

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.