Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given a file like so

First, Last, Age
Cory, Klein, 27
John Jacob, Smith, 30

Is there a command line utility to transpose the contents so the output appears like so

First, Cory, John Jacob
Last, Klein, Smith
Age, 27, 30
share|improve this question
The term you're looking for is transpose: see for example stackoverflow.com/questions/1729824/transpose-a-file-in-bash – Bernhard Jan 8 '13 at 6:27
up vote 7 down vote accepted

CSV parsing is not easily done with POSIX tools only, unless you are using a simplified CSV variant with no quoting (so that commas can't appear in a field). Even then this task doesn't seem easy to do with awk or other text processing to tool. You can use Perl with Text::CSV, Python with csv, R with read.csv, Ruby with CSV, … (All of these are part of the standard library of the respective language except for Perl.)

For example, in Python:

import csv, sys
rows = list(csv.reader(sys.stdin))
writer = csv.writer(sys.stdout)
for col in xrange(0, len(rows[0])):
    writer.writerow([row[col] for row in rows])
share|improve this answer

A quick & dirty solution :

num_lines=$(wc -l < "$file")

for ((i=0; i<num_lines; i++)) {
    cut -d, -f$c "$file" | paste -sd ','
share|improve this answer
what does /tmp/l represent? Additionally, would it not be simpler to loop through the columns rather than lines, something along the lines of for ((i=1; i<=$num_cols; ++i)); do paste -s -d, <(cut -f$i -d, file.txt); done – iruvar Jan 8 '13 at 13:29
Thanks, that was a forgetting harcoded path. – Gilles Quenot Jan 8 '13 at 20:03
Note that this works for OP's input, but only because their data has the same number of rows and columns, which usually is not the case. – tokland Mar 14 at 13:24

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.