# Peeter Joot's (OLD) Blog.

• ## Archives

 Adam C Scott on avoiding gdb signal noise… Ken on Scotiabank iTrade RESP …… Alan Ball on Oops. Fixing a drill hole in P… Peeter Joot's B… on Stokes theorem in Geometric… Exploring Stokes The… on Stokes theorem in Geometric…

• 320,511

## vim: swap two patterns

Posted by peeterjoot on July 22, 2009

Suppose you want to invert something like the following assignment

```pageName->name1 = fakeBPD->pageKey.pageID.pkPageNum;
pageName->name2 = fakeBPD->pageKey.pageID.pkPoolID;
pageName->name3 = fakeBPD->pageKey.pageID.pkObjectID;
pageName->name4 = fakeBPD->pageKey.pageID.pkObjectType;
```

to produce:

```fakeBPD->pageKey.pageID.pkPageNum = pageName->name1;
fakeBPD->pageKey.pageID.pkPoolID = pageName->name2;
fakeBPD->pageKey.pageID.pkObjectID = pageName->name3;
fakeBPD->pageKey.pageID.pkObjectType = pageName->name4;
```

positioning on the first line, this requires nothing more than:

```,+3 s/\(.*\) = \(.*\);/\2 = \1;/
```

Lets break this down. The first part :,+3 specifies a range of lines. For example

```:1,3 s/something/else/
```

this would replace something with else on lines 1-3. If the first line number is left off, the current line is implied, and as above the end line number can be a computed expression relative to the current line (i.e. I did three additional lines on top of the current line).

The line numbers themselves can be patterns. For example:

```:,/^}/ s/something/else/
```

would make the substuition something -> else from the current line to the line that starts with } (^ matches to the beginning of the line). Now, how about the original seach and replace. There a regular expression capture was used. The match pattern was essentially:

```/.* = .*;/
```

but we want to put the two interesting bits in regular expression variables (back references) that can be referred to in the replacement expression. In vim the back references go like \1, \2, …. Different regular expression engines do this differently, and in perl you’d use \$1, \$2 for the back references, and to generate them just /(.*) = (.*);/ instead of \(.*\).