Search and replace in vi (or sed)

Search and replace in vi is both quick and simple:

X,Ys/search/replace/g

(where x – start line number, y – end line number. optional)

One very useful feature is the ability to use parts of the search regular expression within the replace string.

For example, where the selected lines contain values between 2000-2999 and all these values need to be increased by 1000 so that all the values are now in range 3000-3999:

X,Ys/2\([0-9][0-9][0-9]\)/3\1/g

The \1 includes the contents of the 1st regular expression delimited by ( ).

Multiple regular expressions can be reproduced in the replace string. For example, in the file containing:

Surname, Forename
surname, forename

The command:

1,2s/\([a-z]*\), \([a-z]*\)/\2 \1/ig

Results with:

Forename Surname
forename surname

\2 in the replacement string matches the 2nd regular expression in the search string, and likewise for \1 with the 1st regular expression.