How to sort characters in a string?

后端 未结 4 650
伪装坚强ぢ
伪装坚强ぢ 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?

提交回复
热议问题