Paul - The Programmer

simple & stupid
The proper way to access to file in resource by Java
Remove empty lines by VIM global command

Alter the word order in lines by VIM regular expression

paul posted @ Wed, 09 Mar 2011 20:51:48 +0800 in coding life with tags vim regular expression. , 3028 readers

Somehow, I am required to alter the order of word in lines in a text file.

For example, the input text file is like below.

hello world
hello paul
this  is
for   test

I want this file be updated was below.

world hello
paul hello
is  this
test   for

Thanks to regular expression, I do not need to update the lines one after another.

The vim regular expression is a little different than the Perl's. But most of syntax are similar.

\w  : word charaters, includes both alphabet and number characters.

\s   : space characters.

*   : match zero or more preceding character or meta character like \s, \w.

The patterns can be grouped by enclosing with \( and \). 

& :  the whole matched pattern

\0:   the whole matched pattern

\1:   the matched pattern in the first pair of \( and \)

\2:   the matched pattern in the second pair of \( and \)

So, to accomplish the above task, the substitution regular expression is :

:%s/\(\w*\)\(\s*\)\(\w*\)/\3\2\1/

 

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Login *


loading captcha image...
(type the code from the image)
or Ctrl+Enter