How to reverse a list of words in a shell string?
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
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' ' '
You can use awk
as follows:
echo "$str" | awk '{ for (i=NF; i>1; i--) printf("%s ",$i); print $1; }'