How to sort characters in a string?

2019-02-04 11:44发布

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 or will I have to write an awk script to iterate over the string and sort it?

4条回答
一夜七次
2楼-- · 2019-02-04 11:50

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?

查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-04 11:55

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

echo cba | perl -pe 'chomp; $_ = join "", sort split //'
查看更多
▲ chillily
4楼-- · 2019-02-04 11:58
echo cba | grep -o . | sort |tr -d "\n"
查看更多
成全新的幸福
5楼-- · 2019-02-04 12:03

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
  • 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
查看更多
登录 后发表回答