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
  • 1
    Try: unix.stackexchange.com/search?q=transpose Commented Aug 12, 2015 at 4:47
  • 1
    possible duplicate of Transposing rows and columns Commented Aug 12, 2015 at 4: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? Commented Aug 12, 2015 at 9:05

5 Answers 5

4

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. Commented Aug 12, 2015 at 6:16
  • yes right. Still working on that. Commented Aug 12, 2015 at 6:20
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. Commented Aug 12, 2015 at 6:03
2

With sed:

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

2
  • This will remove the last newline of file, and also doesn't work if line contain 0. Commented Aug 12, 2015 at 5:51
  • @cuonglm Thanks for the note, now it works also with a 0. Commented Aug 12, 2015 at 6:02
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' '

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.