-1

I am trying to display some CSV file by switching rows and columns, so that this:

a,b,name
20,10,"Hello World"

Would looks like:

a,20
b,10
name,"Hello World"

For instance in Sqlite one can use the pivot clause, but I'm looking for something more general and not SQL specific.

So is there an easy way to convert rows to columns by splitting them at a given separator (here ,)?

1

1 Answer 1

1
#!/bin/bash
#########################################
# Matrix transpose with Awk
#
# Usage: matrixT file fs ofs
# The last two arguments are optional
#
# Kent
# 2011-07-07
#
#########################################
fs=${2:-" "}
ofs=${3:-" "}
file=$1

awk  -v FS="$fs" -v OFS="$ofs" '{for (i=1;i<=NF;i++) a[i,NR]=$i; }END{
    for(i=1;i<=NF;i++) {
        for(j=1;j<=NR;j++)
            printf "%s%s", a[i,j], (j==NR? ORS:OFS);
    } 
}' "$file"

Sometimes I need do this also quite often, so I wrote a script (see above).

You can do :

theScript.sh file ","  ","
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.