Stochastic Nonsense

Put something smart here.

Transpose or Pivot From Bash

I recently had a set of data in rows that I wanted to put in columns, just like transpose does in excel. Here’s a little ruby script that will do it. Ideally, I’d extend this to take a -F argument to control what the script splits on just like awk.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ cat bin/transpose
#!/usr/bin/ruby

# otherwise reading blocks
exit if STDIN.tty?

lines = []
STDIN.each do |line|
lines << line.strip.split(',').each{ |x| x.strip! }
end

columns = lines.shift
columns = columns.zip(*lines)

columns.each do |column|
puts "#{ column.join(', ') }"
end

usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ echo "col1,0, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 0.999, 1.0
col2,0.0,1.0,1.0,1.0,2.0,2.0,2.0,4.0,5.0,7.0,9.0,14.0,22.0,47.0,85.0,258.0,1127.0,1834676.0" | transpose
col1, col2
0, 0.0
0.001, 1.0
0.005, 1.0
0.01, 1.0
0.05, 2.0
0.1, 2.0
0.2, 2.0
0.3, 4.0
0.4, 5.0
0.5, 7.0
0.6, 9.0
0.7, 14.0
0.8, 22.0
0.9, 47.0
0.95, 85.0
0.99, 258.0
0.999, 1127.0
1.0, 1834676.0