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?
Sort a Python String with Sorted Python comes with a function, sorted() , built-in. This function takes an iterable item and sorts the elements by a given key. The default value for this key is None , which compares the elements directly. The function returns a list of all the sorted elements.
The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.
Firstly, set a string array. string[] values = { "tim", "amit", "tom", "jack", "saurav"}; Use the Sort() method to sort.
sort(char[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of chars into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.
echo cba | grep -o . | sort |tr -d "\n"
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With