Blogs Directory

Monday, April 15, 2013

Interchange two columns in VIM


Sometimes we might be working on the databases where we require swapping of the columns. There may be many ways but what u found most interesting is this method.

1. First we need to provide the range over which the swapping need to be done. In this case the range is lines. If you want to swap the columns across all the lines in the file, then use % sign. % means all lines in the file.

2. Then we need to substitute the existing columns with the changed ordered column. For that we are going to use the substitute command 's'.

3. Then we need to provide the pattern to be matched. In this case the columns to be swapped need to be matched. In the same time we need to have them in the memory so that we can substitute them with the chaged order. For this we can make use of '\(' and '\)' before and after the patterns. This makes the vim to save them in the variable '1', '2'... etc upto '9'.

               \(pattern1\) \(pattern2\)
The space between the two patterns is the delimiter between the columns. It can be anything. I have used space here for the example. If you don't have a regular pattern to be matched then you can use '.*' to match the word like :
               \(.*\) \(.*\)

4. Then we need to specify the pattern to be replaced with. This is done using our saved variable. '1', '2' etc.
                   \1 \2

An example would be like this :

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

:                   command line prompt
%                 on all the lines
s                   substitute
\(.*\)             matches the first word (first column)
space -         matches the space after the name
\(.*\)            matches the second word (i.e, second column)
\2                 variable that holds the second matched word
\1                 variable that holds the first matched word
c                  substitute only on confirmation

No comments :

Post a Comment