today I started to use vim. I get confused at :g
and :%s
commands. So, what is the difference between :g
or :%s
commands?
In vim's normal mode, the g prefix is used for a number of commands. Some commands go somewhere in the document, but other commands deal with file encodings and swapping upper/lower case letters. ga - show character encoding.
created 2001 · complexity basic · version 6.0. Vim provides the :s (substitute) command for search and replace; this tip shows examples of how to substitute.
The key difference is the exclamation mark here. :q will warn you about unsaved changes and will not let you exit. :q! will not warn you.
z doesn't stand for anything.
The Vim command-line editing and history allow you to search through your previous commands, repeat them, or edit them before executing them again. Vi does not support command line completion while Vim allows you to use the Tab key to complete commands, options, and filenames as needed.
:%s/pattern/replace/g is common, the following is nearly equivalent: :g/./s/pattern/replace/g (less common, but basically the with "substitute" command). "$ means "last line in the file"." is interesting to me because vim normally uses $ to represent the end of the line and G to represent the end of the file.
However, because the command was entered while lines were selected, Vim displays the command as: The range '<,'> is entered automatically to identify the lines that were last visually selected (they do not need to be visually selected now). For example, you might type vip to visually select "inner paragraph" (the paragraph holding the cursor).
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: This will execute the search and replace seen earlier on only lines 10 to 15 (inclusive).
: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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With