Search code examples
vimviex

swapping characters in ex


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?


Solution

  • To replace second character in each line to r in vim: :%s/^\(.\)./\1r/:

    • :%s/p/r/ replace pattern p with r 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/.