Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a list of words in a shell string?

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?

like image 206
MOHAMED Avatar asked Dec 30 '14 10:12

MOHAMED


4 Answers

You can use awk as follows:

echo "$str" | awk '{ for (i=NF; i>1; i--) printf("%s ",$i); print $1; }' 
like image 145
Feten besbes Avatar answered Sep 30 '22 15:09

Feten besbes


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' ' ' 
like image 38
Skynet Avatar answered Sep 30 '22 17:09

Skynet


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 
like image 29
anandi Avatar answered Sep 30 '22 17:09

anandi


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.

like image 40
Tom Fenech Avatar answered Sep 30 '22 16:09

Tom Fenech