简体   繁体   English

从 csv 文件中以相反的顺序打印列

[英]Print columns in reverse order from csv file

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.写了python来反转csv文件,但是需要相当长的时间。 Any way to do it in bash?有什么办法可以在 bash 中做到这一点吗?

Using awk :使用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

You can also use sed你也可以使用 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在 shell 中你可以给出 command./reverse_pattern.sh < csv.txt,其中 reverse_pattern.sh 在脚本之上,csv.txt 是输入文件

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

With perl which has a built-in reverse function:使用具有内置reverse功能的perl

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM