What is the difference between :g and :%s commands in vim

:g, short for global, executes a command on all lines that match a regex:

:g/LinesThatMatchThisRegex/ExecuteThisCommand

Example:

:g/hello/d

This will delete (d) all lines that contain hello.

On the other hand, :%s just performs a search (on a regex) and replace throughout the file:

:%s/hello/world/g

The g at the end means global or greedy (this is disputed) so it will replace all occurrences on the line, not just one per line. You can also use the c flag (:%s/hello/world/gc) if you want to confirm each replacement manually.

This command replaces all occurrences of hello with world.

Both the :g and :%s commands support regular expressions.

The s command means substitute and the % means throughout the buffer. So %s means substitute throughout the entire buffer. You can also give a line range:

:10,15s/hello/world/g

This will execute the search and replace seen earlier on only lines 10 to 15 (inclusive).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)