Table of Contents
VIM - Change Content - Change Content for any lines that match a specific pattern
To execute an Ex command for any lines that match a specific pattern.
- Use the global command.
NOTE: The :global command can be used with any Ex command.
- This means that it can also be used in macros by way of the :norm command.
Example
With a file having the following content:
foo foobar barfoo
To delete any lines that start with foo, use the global command:
:g/^foo/d
NOTE: To just see what would match:
- Either use the :p command
:g/^foo/p
- Or just leave off the command altogether as :p is the default behavior.
Use the Global command with Macros
The Global command can be used with any Ex command, meaning it can also be used with macros by way of the :norm command.
For example, search for foo anywhere in the content and then apply the @q register to the matches:
:g/foo/norm @q | update
NOTE: :norm means the first example could be mimicked with:
# Both are the same. :g/^foo/d :g/^foo/norm dd
Use Controls Keys like <Shift> with the Global command
The command to be called would be the :execute command.
NOTE: The :execute command will enable you to provide a string that will be evaluated into an Ex command.
With a file having the following content:
foo bar baz qux
wanting:
foo bar baz qux
Use the following:
:g/^/exe "norm \<s-j>"
NOTE: The <s-j>, which means <Shift-j> in normal mode, causes the following line to be joined to the current line.
- An ! can be used to cause :global to behave in reverse.
- i.e. Apply the command to anything that does not match the given pattern.