ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Beware of the Turing tar-pit in which everything is possible but nothing of interest is easy.
I think sorting data in sed would be ridiculously difficult. Sorting is not part of standard awk (the given awk solution requires GNU awk), but if you felt like restricting yourself to basic tools, it would be not be nearly as hard to implement in awk as compared to sed.
@danielbmartin: I think your solution calls asort() once for every word in the line, for efficiency (only relevant if you have really long lines) one might want to move that call before the loop.
@danielbmartin: I think your solution calls asort() once for every word in the line, for efficiency (only relevant if you have really long lines) one might want to move that call before the loop.
My earlier post failed to give a deserved attribution. The awk solution was originally posted by firstfire on 02-02-12. I simplified it, only a bit.
To demonstrate the efficiency difference, I will pass input with a pathologically long line:
Code:
~/tmp$ time yes | head -1000 | tr '\n' ' ' | gawk '{ split($0, w); s = "";
for (i=1; i <= asort(w); i++)
s = (s w[i] " ");
print s}' >/dev/null
> > >
real 0m2.593s
user 0m2.568s
sys 0m0.008s
~/tmp$ time yes | head -1000 | tr '\n' ' ' | gawk '{ split($0, w); s = ""; wc = asort(w);
for (i=1; i <= wc; i++)
s = (s w[i] " ");
print s}' >/dev/null
> > >
real 0m0.037s
user 0m0.028s
sys 0m0.004s
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.