Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
3  
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

2 Answers 2

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 :

c=1
file=file.txt
num_lines=$(wc -l < "$file")

for ((i=0; i<num_lines; i++)) {
    cut -d, -f$c "$file" | paste -sd ','
    ((c++))
}
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 –  1_CR Jan 8 '13 at 13:29
    
Thanks, that was a forgetting harcoded path. –  sputnick Jan 8 '13 at 20:03

Your Answer

 
discard

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.