Using escaped brackets, you can define a capturing group in a pattern that can be backreferenced in the substitution string with \1
:
$ echo Hello world! | sed 's/\(Hello\) world!/\1 sed/'
Hello sed
With multiple groups:
$ echo one two three | sed 's/\(one\) \(two\) \(three\)/\3 \2 \1/'
three two one
When using extended regular expressions (see Additional Options) parenthesis perform grouping by default, and do not have to be escaped:
$ echo one two three | sed -E 's/(one) (two) (three)/\3 \2 \1/'
three two one
Words consisting of letter, digits and underscores can be matched using the expression
[[:alnum:]_]\{1,\}
:
$ echo Hello 123 reg_exp | sed 's/\([[:alnum:]_]\{1,\}\) \([[:alnum:]_]\{1,\}\) \([[:alnum:]_]\{1,\}\)/\3 \2 \1/'
reg_exp 123 Hello
The sequence \w
is equivalent to [[:alnum:]_]
$ echo Hello 123 reg_exp | sed 's/\(\w\w*\) \(\w\w*\) \(\w\w*\)/\3 \2 \1/'
reg_exp 123 Hello