行の最初と最後の単語を交換するように求めているため、それらを確実にキャプチャする必要があります (上記の回答の多くがそうであるように、最初と 2 番目の単語ではありません)。
echo "hello cruel and unkind world" | sed 's/^\([^ ]*\) \(.*\) \([^ ]*\)$/\3 \2 \1/'
結果として
world cruel and unkind hello
仕組みは次のとおりです。
^\([^ ]*\) - starting at the beginning of the line (^), find as many non-space characters as you can (stops at first space)
note - depending on the flavor of sed you use, there are special symbols to map "a non whitespace, e.g. \S
- the next space is matched but not captured
\(.*\) - capture "everything" after this, until...
\([^ ]*\)$ - a space followed by all non-space characters followed by the end of string
次に、3 つのキャプチャ グループを逆の順序で出力し、その間にスペースを入れると、求めていたものが正確に得られます。