PDA

View Full Version : BASH/sort and a string with spaces



altonbr
July 10th, 2008, 10:37 PM
Is it possible to sort a string of words using sort?


echo 'joe abbey john anirudh steph' | sort

I looked at the man page and thought I could use -t with " " but that didn't seem to work.

HalPomeranz
July 11th, 2008, 12:24 AM
The sort program only works on a line-by-line basis. So if each of your words was on a separate line, then sort would work.

I'm guessing the list of words is in a variable in your shell script? You could do something kind of hack-y like this:



str='joe abbey john anirudh steph'
for i in `echo $str`; do
echo $i
done | sort


That would output the names in sorted order, one per line.

rye_
July 11th, 2008, 12:41 AM
Perl-related scripting languages are especially good at this....

Ruby Code


ruby -e 'puts "joe abbey john anirudh steph".split(/\s+/).sort'


Ryan

ghostdog74
July 11th, 2008, 03:14 AM
Perl-related scripting languages are especially good at this....

any language/tools that provides regexp, string manipulation functions can do this.

ghostdog74
July 11th, 2008, 03:14 AM
Is it possible to sort a string of words using sort?


echo 'joe abbey john anirudh steph' | sort

I looked at the man page and thought I could use -t with " " but that didn't seem to work.



# echo 'joe abbey john anirudh steph'|tr " " "\n"|sort|tr "\n" " "

HalPomeranz
July 11th, 2008, 03:27 AM
# echo 'joe abbey john anirudh steph'|tr " " "\n"|sort|tr "\n" " "


Nice one.

maxadamo
May 2nd, 2009, 02:23 PM
Is it possible to sort a string of words using sort?


echo 'joe abbey john anirudh steph' | sort

I looked at the man page and thought I could use -t with " " but that didn't seem to work.

This is to explain how and when "-t" can be used:

you can see the difference between:
echo -e "1/2/3\n3/3/1"|sort -t/ -k3
echo -e "1/2/3\n3/3/1"|sort

You allow sorting the two rows, using the third field, and the separator is set to "/".
But it's still sorting rows, and not words in the same row.