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
?
You can use awk
as follows:
echo "$str" | awk '{ for (i=NF; i>1; i--) printf("%s ",$i); print $1; }'
Yes, you can try these commands,
For string,
echo "aaaa eeee bbbb ffff cccc"|tr ' ' '\n'|tac|tr '\n' ' '
For the variable,
echo $str|tr ' ' '\n'|tac|tr '\n' ' '
if you need pure shell, no external tools, consider this:
reverse_word_order() {
local result=
for word in $@; do
result="$word $result"
done
echo "$result"
}
reverse_word_order "$str"
Otherwise tac
can help you straight away:
echo -n "$str" | tac -s' '
or
tac -s' ' <<<"$str" | xargs
You could use awk:
echo "aaaa eeee bbbb ffff cccc" | awk '{for(i=NF;i>0;--i)printf "%s%s",$i,(i>1?OFS:ORS)}'
Loop backwards through the fields, printing each one. OFS
is the Output Field Separator (a space by default) and ORS
is the Output Record Separator (a newline).
I'm assuming that you don't want the order of the letters in each word to be reversed.
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