Swap words in VIM
To replace every occurrence of “and” with “OR” and every occurrence of “OR” with “and” in Vim, you can use a :global command with a regular expression to swap them. Here’s how you can do it:
- Open your file in Vim.
- Press
Escto make sure you’re in normal mode. - Use this command:
:%s/\(and\)\|\(OR\)/\=submatch(0) == 'and' ? 'OR' : 'and'/gExplanation:
:%s/– This tells Vim to search and replace throughout the entire file.\(and\)\|\(OR\)– This regular expression matches either “and” or “OR” (note that\|is the “or” operator in Vim’s regex).\=submatch(0) == 'and' ? 'OR' : 'and'– This part uses Vim’s expression evaluation (\=) to check if the match is “and” and replace it with “OR”, otherwise replace “OR” with “and”./g– This flag ensures all occurrences are replaced, not just the first one.
This will swap all “and” with “OR” and vice versa in a single operation.