2

I want my Unix file output, which has each value output on a new line, to be converted into grouped rows as shown below.

Say my output file in Unix looks like this:

jobname
userid
starttime
endtime
jobname2
userid
starttime
endtime

I want the output to be:

jobname1 userid starttime endtime
jobname2 userid starttime endtime
Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
user1596321
  • 21
  • 1
  • 1
  • 2
  • Are you trying to run a bash script? Or Python? Or C++? or ?? – fooOnYou Aug 13 '12 at 20:55
  • What you describe in the question is that you have a column and you want to convert it to several rows, that is, "convert columns to rows" **not** "convert rows to columns" – Stephen P Aug 14 '12 at 00:36

5 Answers5

10

This is a minimal awk solution:

awk 'ORS=NR%4?" ":"\n"' input.txt 

output

jobname userid starttime endtime
jobname2 userid starttime endtime

(If you want to align the fields, pipe to column -t)

kev
  • 155,172
  • 47
  • 273
  • 272
6

This will paste each four consecutive lines as four tab-delimited fields:

cat source_file | paste - - - - > destination_file
Julian TF
  • 465
  • 5
  • 10
1

If you are looking for a shell script, you can do this as the number of lines to be printed in the output seems to have to fixed length:

while read line1; do
  read line2
  read line3
  read line4
  echo $line1 $line2 $line3 $line4 >>output
done <file
P.P
  • 117,907
  • 20
  • 175
  • 238
1

With GNU sed:

tr '\n' ' ' < file | sed -r 's/(\w+ +){4}/&\n/g'
Thor
  • 45,082
  • 11
  • 119
  • 130
0

Kind of ugly, but doesn't require a shell script:

cat outputfile | tr "\n" " " | sed -e 's/\W*\(\w*\) \(\w*\) \(\w*\) \(\w*\)\W*/\1 \2 \3 \4\n/g'
Jon Lin
  • 142,182
  • 29
  • 220
  • 220