根据字母顺序重新排列列数据

根据字母顺序重新排列列数据

我想根据字母顺序更改列数据的顺序

输入

c,a,b
e,k,d

输出

a,b,c
d,e,k

目前,我正在使用下面的代码

awk -F"," -v OFS="," '{ 
if($1<=$2 && $2<=$3) 
{print $1,$2,$3} 
else if($1<=$2 && $3<=$2) 
{print $1,$3,$2} 
else if($2<=$1 && $1<=$3) 
{print $2,$1,$3} 
else if($2<=$1 && $3<=$1) 
{print $2,$3,$1} 
else if($3<=$2 && $2<=$1) 
{print $3,$2,$1} 
else 
{print $3,$1,$2}}' test.txt 

您能帮我提供一个更简单的解决方案来处理具有 4 列或更多列的文件吗

答案1

如果您同意perl

$ perl -F, -lane 'print join ",", sort @F' ip.txt
a,b,c
d,e,k

-F,指定要分割的输入行,作为分隔符,结果可通过@F数组获得

sort @Fjoin将按字母顺序排序,结果数组将使用,分隔符进行组合


GNU awk

$ awk 'BEGIN{PROCINFO["sorted_in"] = "@val_str_asc"}
       {s = ""; c=0; split($0,a,",");
        for(k in a) s = c++ ? s "," a[k] : a[k];
        print s}' ip.txt
a,b,c
d,e,k

gawk 手册:使用预定义的数组扫描顺序有关上面使用的数组排序的详细信息

答案2

使用 GNU awk 进行排序:

$ cat tst.awk
BEGIN {
    FS=OFS=","
}
{
    sub(/\r$/,"")
    print sort($0)
}

function sort(inStr,    arr,idx,sep,outStr) {
    PROCINFO["sorted_in"] = "@val_str_asc"
    split(inStr,arr)
    for (idx in arr) {
        outStr = outStr sep arr[idx]
        sep = OFS
    }
    return outStr
}

$ awk -f tst.awk file
a,b,c
d,e,k

或使用任何 awk,但执行速度会慢得多,因为它会生成一个 shell 来sort为每行输入调用 UNIX:

$ cat tst.awk
BEGIN {
    FS=OFS=","
}
{
    sub(/\r$/,"")
    print sort($0)
}

function sort(inStr,    cmd,line,sep,outStr) {
    gsub(/,/,"\n",inStr)
    cmd = "printf \047%s\n\047 \047" inStr "\047 | sort"
    while ( (cmd | getline line) > 0 ) {
        outStr = outStr sep line
        sep = OFS
    }
    close(cmd)
    return outStr
}

$ awk -f tst.awk file
a,b,c
d,e,k

sub(/\r$/,"")是因为您发布的示例输入中有 DOS 行结尾,但发布的预期输出中没有。

答案3

perl -nlE 'say join ",", sort split ","'   file.txt

解释:

            for each line like "r,d,a":
 "r,d,a"
    ↓          split ","  it
("r","d","a")
    ↓          sort       it
("a","d","r")
    ↓          join ","   it
 "a,d,r"
               say it

相关内容