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

2019-01-23 15:39发布

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?

13条回答
唯我独甜
2楼-- · 2019-01-23 16:19

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' ' '
查看更多
Summer. ? 凉城
3楼-- · 2019-01-23 16:19

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.

查看更多
叼着烟拽天下
4楼-- · 2019-01-23 16:19
/* Shell script to reverse the Input String */    
echo " **** Program to Reverse a String **** "
read -p " Enter Here : " text

echo "You have entered : " $text

echo -n "Reverse of String : "

arr=($text)

arrlength=${#arr[@]}

arrlength=`expr $arrlength - 1`

while [ $arrlength -ge 0 ]
do

echo -n ${arr[arrlength]}
echo -n " "
 arrlength=`expr $arrlength - 1`
done

echo

OUTPUT


**** Program to Reverse a String ***


Enter Here : I love My India

You have entered : I love My India

Reverse of String : India My love I

查看更多
Lonely孤独者°
5楼-- · 2019-01-23 16:22

Here is an awk using do while (not much used here at Stackoverflow)
No extra variable needed i

echo "aaaa eeee bbbb ffff cccc"|awk '{do printf "%s"(NF>1?FS:RS),$NF;while(--NF)}'
cccc ffff bbbb eeee aaaa
查看更多
劳资没心,怎么记你
6楼-- · 2019-01-23 16:27

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 
查看更多
淡お忘
7楼-- · 2019-01-23 16:27

Another pure bash solution:

str='test a is this'; res=""; prev=""
while [ "$prev" != "$str" ]; do res="$res${str##* } "; prev="$str"; str="${str% *}"; done
查看更多
登录 后发表回答