### Problem

You need to substitute columns, whilst editing a file with vi.

### Solution

Okay, bit more complex with this one.

To substitute columns, we bracket off the pattern – like this (*pattern*)

Then we simply use an escaped number to substitute.

### Example

Here is a demo, whilst editing a file with vi:

:%s/(.*) (.*)/2 1/

This says match all lines (%), substitute (s). Match anything up to a space, store in column one. Match anything else, store in column two. Now swop column two with column one.

Here is a run through – unchanged:

a z

b y

c x

d w

e v

f u

g t

h s

i r

j q

k p

l o

m n

The substitute:

:%s/(.*) (.*)/2 1/

The result:

z a

y b

x c

w d

v e

u f

t g

s h

r i

q j

p k

o l

n m

Thank you, This is exactly what I was looking for.

The above regular expression did not work in vi for me. Instead this worked:

%s/\(.*\) \(.*\)/\2 \1/