I am pretty new to vim and ex and I was wondering if anyone could help me with an area I am fuzzy on. I would like to know how to swap characters on every line or occurrence of a pattern. For example How would I swap the first 2 characters of every line in a file. I know it can be done and I'm pretty sure it involves the use of parentheses to store the chars. But thats is all I know. Also, Say I wanted to replace the 2nd char on everyline with some string, how would I do that?
Asked
Active
Viewed 209 times
3 Answers
1
To replace second character in each line to r
in vim: :%s/^\(.\)./\1r/
:
:%s/p/r/
replace patternp
withr
for all lines (because of%
);^
start line;\(
start a group;.
any character (the first in this example);\)
end the group;.
any character (the second in this example);\1
back reference to the first group (the first character in this example);r
replacement text.
To swap two first characters: :%s/^\(.\)\(.\)/\2\1/
.

Andrey
- 2,503
- 3
- 30
- 39
0
Swapping the first two characters on every line:
:%s/^\(.\)\(.\)/\2\1/g
Replacing the second character on every line with "string":
:%s/^\(.\)\(.\)/\1string/g
More info on the substitute command: http://vim.wikia.com/wiki/Search_and_replace

marosoaie
- 2,352
- 23
- 32
0
You can do the following to swap the two first chars of every line in the buffer:
:%norm xp
or:
:%s/\v^(.)(.)/\2\1
You'll need the :global
command to apply the commands above on every line matching a specific pattern:
:g/foo/norm xp
or:
:g/foo/s/\v^(.)(.)/\2\1
Reference:
:help :normal
:help :global
:help :s
:help range

romainl
- 186,200
- 21
- 280
- 313