您要求交换行中的第一个和最后一个单词-因此您需要确保捕获那些(而不是第一个和第二个单词,就像上述许多答案一样)。
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
然后,当您以相反的顺序输出三个捕获组时,中间有一个空格,您会得到您所要求的内容。