Using Substrings, you can reuse parts of the expression to match for the replacement. This is a simple example:
$ date Mon Jul 25 23:59:40 CEST 2005 $ date | sed -n 's/.*\ \(.*\)/\1/p' 2005
Important parts are:
-n | do not output anything not requested |
\( | marks the beginning of the Substring |
\) | marks the end of the Substring |
\1 | matches the first Substring defined in the expression |
/p | print the substitution |
Strangely, the order of evaluation of Regular Expressions works from right to left. The simple example below proofs this:
$ release=`uname -r` $ echo $release 2.6.12-gentoo-r6 $ expr $release : '\(.*\)\..*' 2.6 $ expr $release : '\(.*\)\..*\..*' 2 $ expr $release : '\(.*\..*\)\..*' 2.6 $ expr $release : '\(.*\..*\).*' 2.6.12-gentoo-r6
Clearly to be seen, the “.*” right of the brackets has higher priority than the one inside the brackets.