Reputation: 401
I have two columns:
cats dog
dog cats
I want to swap the two columns:
dog cats
cats dog
Using vim how would i do this?
Upvotes: 18
Views: 13364
Reputation: 31568
Yep, there is such a thing as a swap two columns Vim plugin.
111 222 333 444 555 333 222 111 444 555
111 222 333 444 555 333 222 111 444 555
111 222 333 444 555 → 333 222 111 444 555
111 222 333 444 555 333 222 111 444 555
111 222 333 444 555 333 222 111 444 555
Upvotes: 2
Reputation: 802
Following macro can be used:
qaqqadf A <esc>pj0q99@a
qaq
clears the register a.qa
start recording macro in register a.df
delete till the spaceA
append after the end of line and give a space<esc>p
go to normal mode and paste.j0
go to the first column in next line.q
stop macro aUpvotes: 2
Reputation: 196751
My first idea, a substitution, ended up looking too much like Birei's so I went with AWK (that I don't know very much) used as a filter:
:%!awk '{print $2, $1}'
Upvotes: 38
Reputation: 1641
You can archive this in this easy way, any caracters in first and second column
:%s/\(.\+\)\(\s\+\)\(.\+\)/\3\2\1/g
Upvotes: 2
Reputation: 2738
If the columns take the whole file use this:
:%normal "adt xA <CTRL-v><CTRL-r>a
If it's only a section of the file, make a visual selection end use this:
:'<,'>normal "adt xA <CTRL-v><CTRL-r>a
Explanation:
%
or '<,'>
: Run the following command on the whole file (%
) or in a specific section ('<,'>
);"adt
: Deletes everything until the first space (space not included) and stores the deleted text in the register a
.x
: deletes the trailing space;A
: starts to append text;<CTRL-v><CTRL-R>a
: Enters the <CTRL-r>
command (it will show a ^R
), which inserts the content of the register a
.Upvotes: 1
Reputation: 36272
You can achieve it with a regular expression using \S
for non-blank characters and \s
for blanks, like:
:%s/\v^(\S+)\s+(\S+).*$/\2 \1/
It yields:
dog cats
cats dog
Upvotes: 16