How to sort characters in a string?

后端 未结 4 574
伪装坚强ぢ
伪装坚强ぢ 2020-12-25 14:55

I would like to sort the characters in a string.

E.g.

echo cba | sort-command
abc

Is there a command that will allow me to do this

相关标签:
4条回答
  • 2020-12-25 15:22

    Please find the following useful methods:

    Shell

    Sort string based on its characters:

    echo cba | grep -o . | sort | tr -d "\n"
    

    String separated by spaces:

    echo 'dd aa cc bb' | tr " " "\n" | sort | tr "\n" " "
    

    Perl

    print (join "", sort split //,$_)
    

    Ruby

    ruby -e 'puts "dd aa cc bb".split(/\s+/).sort' 
    

    Bash

    With bash you have to enumerate each character from a string, in general something like:

    str="dd aa cc bb";
    for (( i = 0; i < ${#str[@]}; i++ )); do echo "${str[$i]}"; done
    

    For sorting array, please check: How to sort an array in bash?

    0 讨论(0)
  • 2020-12-25 15:26
    echo cba | grep -o . | sort |tr -d "\n"
    
    0 讨论(0)
  • 2020-12-25 15:46

    This is cheating (because it uses Perl), but works. :-P

    echo cba | perl -pe 'chomp; $_ = join "", sort split //'
    
    0 讨论(0)
  • 2020-12-25 15:46

    Another perl one-liner

    $ echo cba | perl -F -lane 'print sort @F'
    abc
    
    $ # for reverse order
    $ echo xyz | perl -F -lane 'print reverse sort @F'
    zyx
    $ # or
    $ echo xyz | perl -F -lane 'print sort {$b cmp $a} @F'
    zyx
    
    • This will add newline to output as well, courtesy -l option
      • See Command switches for doc on all the options
    • The input is basically split character wise and saved in @F array
    • Then sorted @F is printed


    This will also work line wise for given input file

    $ cat ip.txt 
    idea
    cold
    spare
    umbrella
    
    $ perl -F -lane 'print sort @F' ip.txt 
    adei
    cdlo
    aeprs
    abellmru
    
    0 讨论(0)
提交回复
热议问题