I have a list of words in a string:
str="SaaaaE SeeeeE SbbbbE SffffE SccccE"
I want to reverse it in order to get
"SccccE SffffE SbbbbE SeeeeE SaaaaE"
How I can do that with ash
?
I have a list of words in a string:
str="SaaaaE SeeeeE SbbbbE SffffE SccccE"
I want to reverse it in order to get
"SccccE SffffE SbbbbE SeeeeE SaaaaE"
How I can do that with ash
?
This is a slight adaptation of the Reverse Characters of Lines script in the GNU sed manual:
It makes a few assumptions such as no leading or trailing blanks and all the words being separated by exactly one space. Lines with leading or trailing blanks stay untouched, and lines where the words aren't all separated by exactly one space leave the extra spaces where they are, which might not be what is desired.
The script should work with any POSIX conformant sed and basic regular expressions (BRE). Using GNU sed and extended regular expressions (ERE) would allow for better readability, such as
for the main substitution, but if you're using sed for this problem in the first place, readability is probably not the top concern.
This works in
sh
(I don't haveash
so can't verify that):use it like this:
Here are some alternatives. First, one that doesn't use the C-style
for
:The next one (from here) works where substitutions don't (e.g. on Android)
I was trying to find a solution that worked in an Android script, where
sh
doesn't like C-stylefor
or complex substitution operations. I ended up with the last example because it uses neither.If using Haskell is acceptable, there is a nice tool called hawk (haskell-awk) which can do this very easily. First you need to install it:
Then:
You need
~/.cabal/bin
in yourPATH
to findhawk
.BASH
This is the function that I use, (not tested in ash)
DASH
(also works in bash, but some people seem to have an aversion to echo)
sed grouping:
You can use
awk
as follows: