I am trying to use sed to switch the order of the first and last word in a sentence, since I don't think I understand how "greedy" regular expression is in this case. I failed miserably just for a sentence of three words.
$ echo hello world mike | sed 's/\([a-z]*\).* \([a-z]*\).*/\2 \1/'
mike hello
Why the output is not "world hello mike"? Some extra information that might be helpful.
\1 \2 are the first and second regular expression matches
I was following a tutorial here.
My final goal is to switch the order of the first and last word in a sentence regardless of how many words there are in there.
You didn't include the hello
part as one of your capture groups, so it doesn't get output. Try:
$ sed -E 's/([a-z]+) (.+) ([a-z]+)/\3 \2 \1/' <<< "hello world mike"
mike world hello
$ sed -E 's/([a-z]+) (.+) ([a-z]+)/\3 \2 \1/' <<< "hello world foo bar baz mike"
mike world foo bar baz hello
(Note: I also removed your useless use of echo.)
You can also replace the [a-z]
with [[:alpha:]]
to handle capital letters, too:
$ sed -E 's/([[:alpha:]]+) (.+) ([[:alpha:]]+)/\3 \2 \1/' <<< "Hello world Mike"
Mike world Hello
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With