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条回答
Viruses.
2楼-- · 2019-01-23 16:42

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):

#!/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

查看更多
登录 后发表回答