How to sort characters in a string?

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

提交回复
热议问题