4reel77
4reel77

Reputation: 401

VIM: swap two columns separated by space

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

Answers (6)

Serge Stroobandt
Serge Stroobandt

Reputation: 31568

«Swap two columns» plugin

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

dvk317960
dvk317960

Reputation: 802

Following macro can be used:

qaqqadf A <esc>pj0q99@a
  1. qaq clears the register a.
  2. qa start recording macro in register a.
  3. df delete till the space
  4. A append after the end of line and give a space
  5. <esc>p go to normal mode and paste.
  6. j0 go to the first column in next line.
  7. q stop macro a
  8. 99@a run this macro 99 times (assuming you have 99 columns left)

Upvotes: 2

romainl
romainl

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

c4f4t0r
c4f4t0r

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

Magnun Leno
Magnun Leno

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

Birei
Birei

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

Related Questions