Keep It Simple, Stupid PerlMonks

### Re: Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell)

by ambrus (Abbot)
 on Sep 09, 2008 at 15:46 UTC ( #710122=note: print w/replies, xml ) Need Help??

This thread has no sed solution yet?

The following program reads a single line, and gives its words in reverse.

sed 's/^/@/;:;s/$$.*@$$[ \t]*$$[^ \t][^ \t]*$$/\2 \1/;t;s/ *@.*//;q'
[download]

(This works in GNU sed. If you use another sed, you may need to change the semicolons to new lines, and the \t escapes to real tab characters.)

This really breaks if the input contains an at-sign. If you need such inputs, change the at-sign to some other character that doesn't occurr in the input, or use the following more complicated snippet.

sed 's/@/@a/g;s/^/@s/;:;s/$$.*@s$$[ \t]*$$[^ \t][^ \t]*$$/\2 \1/;t;s/
+*@s.*//;s/@a/@/g;q'
[download]

Create A New User
Node Status?
node history
Node Type: note [id://710122]
help
Chatterbox?
 [thezip]: Is there an analogy for '&' (ie. run commandline process in background) for Windows commandline? [Corion]: thezip: start "some title" path\to\that\ application, but that will open another console window [Corion]: thezip: If you want to confuse your users, use system(1, "that\\command" );, which will make Perl launch it in the background [Corion]: That will keep the console window open even though the user can't type into it anymore [thezip]: So I have a script that generates a log file. After script completion, I want tohave VIM open this logfile. [thezip]: i don't get the command line "back" until I close VIM. No what I want to happen...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (14)
As of 2017-03-27 18:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should Pluto Get Its Planethood Back?

Results (321 votes). Check out past polls.