Command structure resembles substitute command- :g/re/command will run
command over all lines (not words) matching the regular expresson pattern
re
NOTE
You can also run the command on all lines NOT matching the pattern
rewith command:g!/re/command
1. Print matching lines
:g/rewill print at the bottom of the screen all lines matching patternre(default commandpis used here)- The same result can be achieved with
:g/re/p
2. Delete matching lines
:g/console/d _deletes all lines matching patternconsoleand puts them in black hole register_:g!/console/dwill delete lines not matching patternconsole
3. Play macro
:g/pattern/normal @aplays theamacro on all lines matching pattern:g/pattern/normal A.appends a dot.on all lines matching pattern
4. Grep tricks
:g/console/g/two/dis an example of recursive commandconsolefirst matches lines containingconsole- and then second g filters out matches containing
twofrom the earlier matched - then applies
dcommand
:g/pattern1/,/pattern2/commandmakes Vim will apply the command within pattern1 AND pattern2^$matches empty lines (with no character):g/^$/,/./jbasically matches empty lines (^$) and non empty lines (.) and joins them (j)- Delimiter can be changed like the substitute command, use any character except for alphabets, numbers, ”, |, and .
:g@console@ddeletes all lines containing console
5. Combine g and s
- g and s command can be conviniently combined
:g/one/s+const+let+gmatches lines containingone- and then uses the substitute to replace
constwithlet(last g for applying substitute on all matches within the matched lines) - one could also use
g/one/s/const/let/g
6. Copy and move
:g/TODO/t $copies all lines matching patternTODOat the end of file (:h :copy)- Invert also works,
:g!/TODO/t $will copy everything except TODOs at end of file :g/TODO/m $moves all TODOs instead of copying them