Sort entries of lines using shell

前端 未结 4 1577
-上瘾入骨i
-上瘾入骨i 2021-01-24 17:31

Considering the following input and output:

  infile   |   outfile
1 3 5 2 4  |  1 2 3 4 5
2 4 5      |  2 4 5
4 6 2 1    |  1 2 4 6

Is there a

4条回答
  •  忘掉有多难
    2021-01-24 18:11

    Its not pretty (definitely not a 1-liner), but you can sort a line using only builtin shell commands, however for short lines it may be faster than repeatedly calling external functions.

    #!/bin/sh
    sortline(){
    for x in $@;do
        [ ! "$FIRST" ] && FIRST=t && set --
        i=0
        while [ $i -le $# ];do
            [ $x -lt $((${@:$((i+1)):1})) ] && break || i=$((i+1))
        done
        set -- ${@:1:$i}  $x   ${@:$((i+1)):$(($#-$i))}
    done
    echo $@
    }
    while read LINE || [ "$LINE" ];do
        sortline $LINE
    done <$1 >$2
    

    Edit: btw this is a selection sort algorithm in case anyone wondered

    Edit2: this is for numerical values only, for strings you would need to use some comparison like [ "$x" -lt "${@:$((i+1)):1}" ] (unchecked),however I use this C program for strings (I just call it qsort), but it could be modified using atoi on argv:

    #include 
    #include 
    static inline int cmp(const void *a, const void *b){
       return strcmp(*(const char **)a, *(const char **)b);
    }
    
    int main(int argc, char *argv[]){
        qsort(++argv, --argc, sizeof(char *), cmp);
        while (argc){
          write(1,argv[0],strlen(argv[0]));
          write(1,(--argc && argv++)?"\t":"\n",1);
       }
    }
    

提交回复
热议问题