25 examples of vi / vim substitution commands

In this article, we will see the commonly used vi substitution commands. All the below commands are to be given in escape mode:

Common tricks:
1. To replace the 1st occurrence of 'a' with 'A' in every line:

:%s/a/A/

2. To replace the all the occurences of 'a' with 'A'

:%s/a/A/g

g is for global substitution, ie. substitution for all matches.
3. To replace 'e' with 'E' only in the current line:

:s/e/E/g


4. To delete all the occurrences of xyz:

:%s/xyz//g

5. To add a comma at the end of each line:

:%s/$/,/

6. To insert '#' at the beginning of every line:

:%s/^/#/

7. To insert '#' at the beginning of lines from 4 to 6:

:4,6s/^/#/

8. To insert '#' at the beginning of lines from 5th till end:

:5,$s/^/#/

9. To remove the 1st character from the 1st line till the current line:

:1,.s/.//

10. To remove the pattern starting with "abc" till the end of the line:

:%s/abc.*//

11. To replace the current line with xyz:

:s/.*/xyz/

12. To remove the leading spaces in all lines:

:%s/^ *//

13. To remove the trailing spaces in all lines:

:%s/ *$//

14. To replace a set of spaces with a single space(squeeze spaces):

:%s/  */ /g

Nice ones:
15. To capitalize the first character of every line:

:%s/./\u&/

16. To capitalize the entire file:

:%s/.*/\U&/

17. To change to lower case all the lines:

:%s/.*/\L&/

18. To encapsulate all the lines with brackets:

:%s/.*/(&)/

19. To insert a string "XYZ" after the 3rd character:

:%s/.../&XYZ/

20. To insert a string "XYZ" before the 3rd last character:

:%s/...$/XYZ&/

Tricky Ones:
21. To remove all but the 1st 3 characters of every line:

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

22. To remove all but for the last 3 characters of every line:

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

In other words, this just retains the last 3 characters of every line and deletes the rest.
23. To remove 20 characters from the beginning of every line:

:%s/\(.\{20\}\).*/\1/

The ... notation above can be used only for lesser number of characters. This example is for bigger numbers.
24. To swap the words present in a line(assuming lines contain only 2 words):

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

25. To capitalize the first word, and capitalize only the 1st character of 2nd word(assuming lines contain only 2 words):

:%s/\(.*\) \(.*\)/\U\1 \u\2/