Vi Swap Columns


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



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.



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



[tags]UNIX, vi, regular expression, Unix Coding School[/tags]


If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *