如何逆轉shell字符串中的單詞列表?

[英]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?

我怎么能用灰來做呢?

12 个解决方案

#1


15  

You can use awk as follows:

你可以使用awk如下:

echo $str | awk '{ for (i=NF; i>1; i--) printf("%s ",$i); print $1; }'

#2


8  

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' ' '

#3


5  

You could use awk:

您可以使用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).

循環遍歷字段,打印每個字段。OFS是輸出字段分隔符(默認為空格),而ORS是輸出記錄分隔符(換行符)。

I'm assuming that you don't want the order of the letters in each word to be reversed.

我假設你不希望每個單詞的字母順序顛倒。

#4


4  

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

這是一個使用do時的awk(在Stackoverflow上使用不多),不需要額外的變量i

echo "aaaa eeee bbbb ffff cccc"|awk '{do printf "%s"(NF>1?FS:RS),$NF;while(--NF)}'
cccc ffff bbbb eeee aaaa

#5


1  

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:

如果使用Haskell是可以接受的,那么有一個很好的工具叫做hawk (haskell-awk),它可以很容易地做到這一點。首先需要安裝:

$ cabal install haskell-awk

Then:

然后:

$ echo $str | hawk -m reverse

You need ~/.cabal/bin in your PATH to find hawk.

你需要~ /。在你找到老鷹的路上。

#6


1  

if you need pure shell, no external tools, consider this:

如果您需要純shell,沒有外部工具,請考慮如下:

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:

否則tac可以立即幫助你:

echo -n "$str" | tac -s' '

or

tac -s' ' <<<"$str" | xargs 

#7


1  

sed grouping:

sed分組:

str="SaaaaE SeeeeE SbbbbE SffffE SccccE"

echo $str | sed 's/\(.* \)\(.* \)\(.* \)\(.* \)\(.*\)/\5 \4\3\2\1/g'

#8


1  

This works in sh (I don't have ash so can't verify that):

這在sh(我沒有ash,所以無法驗證):

reverse() {
    for (( i = ${#*}; i > 0; i-- ))
    {
        echo ${!i}
    }
}

use it like this:

使用它是這樣的:

$ reversed=$(reverse foo bar baz)
$ echo $reversed
baz bar foo

Here are some alternatives. First, one that doesn't use the C-style for:

這里有一些備選方案。首先,一個不使用c風格的:

reverse() {
    while [ ${#*} -gt 0 ]
    do
      echo ${*: -1}
      set -- "${@:1:$(($#-1))}"
    done
}

The next one (from here) works where substitutions don't (e.g. on Android)

下一個(從這里開始)適用於沒有替換的地方(例如在Android上)

reverse() {
    if [ "$#" -gt 0 ]; then
        local arg=$1
        shift
        reverse "$@"
        printf '%s\n' "$arg"
    fi
}

I was trying to find a solution that worked in an Android script, where sh doesn't like C-style for or complex substitution operations. I ended up with the last example because it uses neither.

我試圖找到一個適用於Android腳本的解決方案,在這個腳本中,sh不喜歡c樣式進行復雜的替換操作。我最后舉了最后一個例子,因為它兩個都不用。

#9


0  

/* 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

弦的倒轉:印度我的愛

#10


0  

Another pure bash solution:

另一個純bash解決方案:

str='test a is this'; res=""; prev=""
while [ "$prev" != "$str" ]; do res="$res${str##* } "; prev="$str"; str="${str% *}"; done

#11


0  

If the input is to be read from file (as asked here: read line reverse from a file), I created the following bash script that prints words of each line in reverse without changing the order of lines of the file (I needed this e.g. when reading words RTL instead of LTR in say chinese, etc):

如果要讀取輸入文件(要求:讀行反向從文件),我創建了以下bash腳本,每行打印的話反過來不改變文件的命令行(我需要閱讀文字時,這如RTL LTR說中國,而是等):

#!/bin/bash

fileName="$1"
outputFile="ReversedFile.npp"

echo > ${outputFile}
lineCount=`cat $fileName | wc -l`
for ((lineNum=1; ${lineNum} <= ${lineCount}; lineNum++))
do
    echo
    echo "Processing Line ${lineNum} of ${lineCount} ..."

    lineOfFile="`cat $fileName | head -${lineNum} | tail -1`"
    echo "${lineOfFile}"

    rm -f wordFile.txt
    for eachWord in `echo "${lineOfFile}"`
    do
        echo "${eachWord}" >> wordFile.txt
    done

    if [ -e wordFile.txt ]; then
        thisLine=""
        wordCount=`cat wordFile.txt| wc -l`
        for ((wordNum=${wordCount}; ${wordNum}>=1; wordNum--))
        do
            wordOfLine="`cat wordFile.txt | head -${wordNum} | tail -1`"
            echo "${wordNum} of ${wordCount} is ${wordOfLine}"
            thisLine+="${wordOfLine} "
        done
        echo "output"
        echo "${thisLine}"
        echo "${thisLine}" >> ${outputFile}
        rm -f wordFile.txt
    fi
done

echo
echo "Output in File ${outputFile}"


Notes:
1) Make sure the input file is in UNIX EOL format otherwise last word might be truncated from each line
2) Some error checks might have been omitted for sake of simplicity

注意:1)確保輸入文件是UNIX EOL格式的,否則最后一個詞可能會從每一行中刪去

#12


0  

BASH

This is the function that I use, (not tested in ash)

這是我使用的函數(未在ash中測試)

#reverse_word_order
function rwo(){ tr ' ' '\n'<<<"$@"|tac|tr '\n' ' ';}
echo $(rwo 'Hello There I am You')
#based on https://stackoverflow.com/a/27703859/1153645

DASH

(also works in bash, but some people seem to have an aversion to echo)

(同樣適用於bash,但有些人似乎不喜歡重復)

rwo(){ echo "$*"|tr ' ' '\n'|tac|tr '\n' ' ';}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/12/30/72f4433ddff0f9dd18fb649b2e98360a.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com