1

Input file

cityId;cityName;numOfBranches;numOfAtms
1;san bruno;7;11
3;milbrae;12;27

I want to print columns in reverse order as shown below:

numOfAtms;numOfBranches;cityName;cityId
11;7;san bruno;1
27;12;milbrae;3

Wrote python to reverse csv file, but it takes considerable time. Any way to do it in bash?

3 Answers 3

6

Using awk:

awk 'BEGIN{FS=OFS=";"} {s=$NF; for (i=NF-1; i>=1; i--) s = s OFS $i; print s}' file
numOfAtms;numOfBranches;cityName;cityId
11;7;san bruno;1
27;12;milbrae;3
Sign up to request clarification or add additional context in comments.

1 Comment

thats the exact thing I was looking for. +1
0

You can also use sed

    while read line
    do
        echo $line | sed s/'\(.*\);\(.*\);\(.*\);\(.*\)/\4;\3;\2;\1/'
    done

in shell you can give command ./reverse_pattern.sh < csv.txt, where reverse_pattern.sh is above script and csv.txt is input file

you can make it generic by using this script

            #!/bin/bash
            outputpat=
            inputpat=
            patternform=
            delimiter=\;

            #calulate num delimiter and form pattern
            form_pattern()
            {
                    count=$(echo "$1"|grep -o "$delimiter"| wc -w)
                    for((i=count+1;i>1;i--))
                    do
                            outputpat="$outputpat\\$i$delimiter"
                    done

                    outputpat="$outputpat\\$i"    #last word not followed by ;

                    for((i=0;i<count;i++))
                    do
                            inputpat="$inputpat\\(.*\\)$delimiter"
                    done
                    inputpat="$inputpat\\(.*\\)" #last word not followed by ;
                    patternform=yes
            }

            while read line
            do
                    if [ -z $patternform ]
                    then
                            form_pattern $line
                    fi
                    echo $line | sed s/$inputpat/$outputpat/
            done

2 Comments

Yes Varun, another trick. One problem: How can we make it generic so as to work with any number of columns in the input file ?
I have made it generic. See the above program
0

With perl which has a built-in reverse function:

$ perl -F';' -lane 'print join ";", reverse @F' ip.csv
numOfAtms;numOfBranches;cityName;cityId
11;7;san bruno;1
27;12;milbrae;3

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.