Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed switch the order of first and last word

Tags:

regex

sed

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. \1 \2 are the first and second regular expression matches

  2. 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.

like image 375
B.Mr.W. Avatar asked Dec 06 '22 04:12

B.Mr.W.


1 Answers

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
like image 52
Carl Norum Avatar answered Dec 17 '22 20:12

Carl Norum