#[1]Edit [2]Vim Tips Wiki (en) [3]copyright [4]Vim Tips Wiki Atom feed

FANDOM

  [5]Games [6]Movies [7]TV [8]Video
  Wikis
    * [9]Explore Wikis
    * [10]Community Central
    * [11]Start a Wiki

  Search
  ____________________ (BUTTON) (BUTTON)
    * [12]Sign In
    * Don't have an account?
      [13]Register

  [14]Start a Wiki

  [15]Vim Tips Wiki
  [16]Vim Tips Wiki
  1,640 Pages
  [17]Add new page

    * [18]Community portal
    * [19]To do
    * Explore
         + [20]Wiki Activity
         + [21]Random page
         + [22]Community
         + [23]Videos
         + [24]Images

  in:
  [25]VimTip, [26]Searching

Power of g

  [27]Edit
    * [28]Edit source
    * [29]History
    * [30]Talk (0)

  [31]Share
    __________________________________________________________________

  [32]Tip 227 [33]Printable [34]Monobook [35]Previous [36]Next

  created 2002 · complexity intermediate · author Arun Easi · version 6.0
    __________________________________________________________________

  The global command :g is very useful. Here are some examples showing
  the power of :g.

Contents

  [[37]show]

Brief explanation of :g[38] [yH5BAEAAAEALAAAAAABAAEAQAICTAEAOw%3D%3D] Edit

:[range]g/pattern/cmd

  This acts on the specified [range] (default whole file), by executing
  the Ex command cmd for each line matching pattern (an Ex command is one
  starting with a colon such as :d for delete). Before executing cmd, "."
  is set to the current line.

Examples[39] [yH5BAEAAAEALAAAAAABAAEAQAICTAEAOw%3D%3D] Edit

  Display context (5 lines) for all occurrences of a pattern.
:g/pattern/z#.5
" Same, but with some beautification.
:g/pattern/z#.5|echo "=========="

  Delete all lines matching a pattern.
:g/pattern/d

  Delete all lines that do not match a pattern. The commands shown are
  equivalent (v is "inverse").
:g!/pattern/d
:v/pattern/d

  Delete all blank lines (^ is start of line; \s* is zero or more
  whitespace characters; $ is end of line)
:g/^\s*$/d

  Double space the file (^ is start of line which matches each line).
:g/^/pu =\"\n\"
" Alternative (:put inserts nothing from the blackhole register)
:g/^/pu _

  Copy all lines matching a pattern to end of file.
:g/pattern/t$

  Move all lines matching a pattern to end of file.
:g/pattern/m$

  Copy all lines matching a pattern to register 'a'.
qaq:g/pattern/y A

         Explanation qaq is a trick to clear register a (qa starts
         recording a macro to register a, then q stops recording, leaving
         a empty). y A is an Ex command ([40]:help :y). It yanks the
         current line into register A (append to register a).

  Increment each number at the start of a line, from the current line to
  end-of-file, by one (the exclamation mark in :normal! means this will
  work even if Ctrl-A has been mapped to perform a function other than
  its default of incrementing a number).
:.,$g/^\d/exe "normal! \<C-A>"

  Comment lines containing "DEBUG" statements in a C program.
" using :normal
g/^\s*DEBUG/exe "norm! I/* \<Esc>A */\<Esc>"
" using :substituting
g/^\s*DEBUG/s!.*!/* & */!

  Reverse lookup for records (say an address book, with Name at
  start-of-line and fields after a space).
:g/pattern/?^\w?p "if only name is interesting
:g/pattern/ka|?^\w?p|'ap "if name and the lookup-line is interesting
:g/pattern/?^\w?|+,/^[^ ]/-1p "if entire record is interesting

         Explanation See [41]:help :range for the meaning of the
         constructs in the [cmd] portion of the :g commands.

  Reverse a file (just to show the power of g).
:g/^/m0

         Explanation According to [42]:help multi-repeat, :g and its
         cousin :v work in a two-pass manner. The first pass of :g marks
         every line matching {pattern}, while the second pass (apparently
         performed starting at the file's beginning and proceeding to the
         end) performs the [cmd]. The above use of :g takes advantage of
         the order the lines are processed in (which is probably okay,
         though probably not technically guaranteed). It works by first
         marking every line, then moving the first marked line to the top
         of the file, then moving the second to the top of the file
         (above the line moved previously), then the third marked line
         (again above the previously moved line), and so on until the
         last line in the file is moved to the top, effectively reversing
         the file. Note that if :g processed lines in any order other
         than from top to bottom, this command would not work.

  Add text to the end of a line that begins with a certain string.
:g/^pattern/s/$/mytext

Deleting many lines[43] [yH5BAEAAAEALAAAAAABAAEAQAICTAEAOw%3D%3D] Edit

  The command :g/pattern/d performs :d on all lines matching the pattern,
  see [44]:help :delete. When a line is deleted, it is first copied to a
  register—since no register is specified, the default (unnamed) register
  is used. If many thousands of lines are deleted, the copy process can
  take a significant time. To avoid that waste of time, the blackhole
  register (_) can be specified because any copy or cut into the
  blackhole register performs no operation.

  Fast delete of all lines matching a pattern.
:g/pattern/"_d

Notes[45] [yH5BAEAAAEALAAAAAABAAEAQAICTAEAOw%3D%3D] Edit

  Some explanation of commands commonly used with :g
:2,8co15  "copy lines 2 through 8 after line 15
:4,15t$   "copy lines 4 through 15 to end of document (t == co)
:-t$      "copy previous line to end of document
:m0       "move current line to line 0 (i.e. the top of the document)
:.,+3m$-1 "current line through current+3 are moved to the lastLine-1 (i.e. next
to last)
    __________________________________________________________________

  Since commands used with :g are Ex commands, searching for help should
  include the colon.
:help :<help-topic>
:help :k   "example

References[46] [yH5BAEAAAEALAAAAAABAAEAQAICTAEAOw%3D%3D] Edit

    * [47]:help ex-cmd-index provides a list of Ex commands.
    * [48]:help 10.4 is the section of the user manual discussing
      the :global command.
    * [49]:help multi-repeat talks about both the :g and :v commands.

Comments[50] [yH5BAEAAAEALAAAAAABAAEAQAICTAEAOw%3D%3D] Edit

  Over a range defined by marks a and b, operate on each line containing
  pattern. The operation is to replace each pattern2 with string.
:'a,'bg/pattern/s/pattern2/string/gi
    __________________________________________________________________

  Run a macro on matching lines (example assuming a macro recorded as
  'q'):
:g/pattern/normal @q
    __________________________________________________________________

  To delete (subsequent) duplicate lines from a file:
:g/^\(.*\)\(\r\?\n\1\)\+$/d
:%!uniq

  To just view the duplicates use:
/^\(.*\)\(\r\?\n\1\)\+$
    __________________________________________________________________

  Compress multiple occurrences of blank lines into a single blank line
:v/./,/./-j

  Use :helpgrep '\/,\/' *.txt for an explanation.

  I'll break down this incredible collapse-multiple-blank-lines command
  for everyone, now that I finally figured out how it works.

  First, however, I'll rewrite it this way to illustrate that some of
  those slashes have totally different meaning than others:
:v_._,/./-1join

  Note that to delimit expressions like these, just about any symbol can
  be used in place of the typical slashes... in this case, I used
  underscores. What we have is an inverse search (:v, same as :g!) for a
  dot ('.') which means anything except a newline. So this will match
  empty lines and proceed to execute [command] on each of them.
:v_._[command]

  The remaining [command] is this, which is a fancy join command,
  abbreviated earlier as just 'j'.
,/./-1join

  The comma tells it to work with a range of lines:
:help :,

  With nothing before the comma, the range begins at the cursor, which is
  where that first blank line was. The end of the range is specified by a
  search, which to my knowledge actually does require slashes. The slash
  and dot mean to search for anything (again), which matches the nearest
  non-empty line and offsets by {offset} lines.
/./{offset}

  The {offset} here is -1, meaning one line above. In the original
  command we just saw a minus sign, to which vim assumes a count of 1 by
  default, so it did the same thing as how I've rewritten it, but simply
  with one character fewer to type.
/./-1

  There is a caveat about join that makes this trick possible. If you
  specify a range of only one line to "join", it will do nothing. For
  example, this command tells vim to join into one line all lines from 5
  to 5, which does nothing:
:5,5join

  In this case, any time you have more than one empty line (the case of
  interest), the join will see a range greater than one and join them
  together. For all single empty lines, join will leave it alone.

  There's no good way use a delete command with :v/./ because you have to
  delete one line for every empty line you find. Join turned out to be
  the answer.

  This command only merges truly "empty" lines... if any lines contain
  spaces and/or tabs, they will not be collapsed. To make sure you kill
  those lines, try this:
:v/^[^ \t]\+$/,/^[^ \t]\+$/-j

  Or, to just clean such lines up first,
:%s/^[ \t]\+$//g
    __________________________________________________________________

  Here is a 'g' version that does the same thing as that last 'v' command
:g/^[ <TAB>]*$/,/[^ <TAB>]/-j

  However, all the above blank line merging method fails to merge
  multiple blank lines at the end of a file. The solution is to add then
  remove an extra line at the end of the file. As such this is the
  complete blank line compressor command...
:$s/$/\\rZ/
:g/^[ <TAB>]*$/,/[^ <TAB>]/-j
:$d

  Or in the form of an easy to use macro, which also tries to return to
  to your original place in the file.
:map QE mz:$s/$/\\rZ/<CR>:g/^[ <TAB>]*$/,/[^ <TAB>]/-j<CR>Gdd`z
    __________________________________________________________________

  As always, There's More Than One Way To Do It:
:%s/^$\n^$//g

  This uses a substution (s/foo/bar/) that matches two consecutive blank
  lines and turns them into one. Applied globally (%), and multiple times
  to the same line (g), this works exactly as you'd want it to.
    __________________________________________________________________

  Another way to collapse empty lines, including whitespace, is:
:%s/^\_s\+/\r/g

  \_s matches whitespace (space and tab) including end of line, \+
  matches 1 or more of those, as many as possible, \r inserts carriage
  return specific to file format (unix-dos-mac).
  Retrieved from "[51]https://vim.fandom.com/wiki/Power_of_g?oldid=40531"

  [52]Categories:
    * [53]VimTip
         +
         +
    * [54]Searching
         +
         +
    * (BUTTON) Add category ____________________

  (BUTTON) Cancel (BUTTON) Save
  Community content is available under [55]CC-BY-SA unless otherwise
  noted.

Fan Feed

  Explore Wikis
    * [56][56?cb=20191109223830]
      Flipline Studios Fanon Wiki
    * [57][56?cb=20190910004306]
      Xavier Riddle and the Secret Museum Wiki
    * [58][56?cb=20190524222222]
      Amphibia Wiki

Explore properties

    * [59]Fandom
    * [60]Gamepedia
    * [61]D&D Beyond
    * [62]Muthead
    * [63]Futhead

Follow Us

    *
    *
    *
    *
    *

Overview

    * [64]About
    * [65]Careers
    * [66]Press
    * [67]Contact
    * [68]Terms of Use
    * [69]Privacy Policy
    * [70]Global Sitemap
    * [71]Local Sitemap

Community

    * [72]Community Central
    * [73]Support
    * [74]Help
    * [75]Do Not Sell My Info

Advertise

    * [76]Media Kit
    * [77]Contact

Fandom Apps

  Take your favorite fandoms with you and never miss a beat.

    *
    *

  D&D Beyond
    *
    *

  Vim Tips Wiki is a FANDOM Lifestyle Community.
  [78]View Mobile Site

  [79][wikiabarIcon.png] JokeyPsych [80][wikiabarIcon.png] EndgameHonest
  [81][wikiabarIcon.png] GalaxyQuest

References

  Visible links
  1. https://vim.fandom.com/wiki/Power_of_g?action=edit
  2. https://vim.fandom.com/opensearch_desc.php
  3. https://www.fandom.com/licensing
  4. https://vim.fandom.com/wiki/Special:RecentChanges?feed=atom
  5. https://www.fandom.com/topics/games
  6. https://www.fandom.com/topics/movies
  7. https://www.fandom.com/topics/tv
  8. https://www.fandom.com/video
  9. https://www.fandom.com/explore
 10. https://community.fandom.com/wiki/Community_Central
 11. https://community.fandom.com/wiki/Special:CreateNewWiki
 12. https://www.fandom.com/signin?redirect=https://vim.fandom.com/wiki/Power_of_g
 13. https://www.fandom.com/register?redirect=https://vim.fandom.com/wiki/Power_of_g
 14. https://community.fandom.com/wiki/Special:CreateNewWiki
 15. https://vim.fandom.com/wiki/Power_of_g
 16. https://vim.fandom.com/wiki/Power_of_g
 17. https://vim.fandom.com/wiki/Special:CreatePage
 18. https://vim.fandom.com/wiki/Vim_Tips_Wiki:Community_Portal
 19. https://vim.fandom.com/wiki/Vim_Tips_Wiki:Todo
 20. https://vim.fandom.com/wiki/Special:WikiActivity
 21. https://vim.fandom.com/wiki/Special:Random
 22. https://vim.fandom.com/wiki/Special:Community
 23. https://vim.fandom.com/wiki/Special:Videos
 24. https://vim.fandom.com/wiki/Special:Images
 25. https://vim.fandom.com/wiki/Category:VimTip
 26. https://vim.fandom.com/wiki/Category:Searching
 27. https://vim.fandom.com/wiki/Power_of_g?veaction=edit
 28. https://vim.fandom.com/wiki/Power_of_g?action=edit
 29. https://vim.fandom.com/wiki/Power_of_g?action=history
 30. https://vim.fandom.com/wiki/Talk:Power_of_g?action=edit&redlink=1
 31. https://vim.fandom.com/wiki/Power_of_g
 32. https://vim.fandom.com/wiki/Power_of_g
 33. https://vim.fandom.com/wiki/Power_of_g?printable=yes
 34. https://vim.fandom.com/wiki/Power_of_g?useskin=monobook
 35. https://vim.fandom.com/wiki/VimTip225
 36. https://vim.fandom.com/wiki/VimTip228
 37. https://vim.fandom.com/wiki/Power_of_g
 38. https://vim.fandom.com/wiki/Power_of_g?action=edit&section=1
 39. https://vim.fandom.com/wiki/Power_of_g?action=edit&section=2
 40. http://vimdoc.sourceforge.net/cgi-bin/help?tag=:y
 41. http://vimdoc.sourceforge.net/cgi-bin/help?tag=:range
 42. http://vimdoc.sourceforge.net/cgi-bin/help?tag=multi-repeat
 43. https://vim.fandom.com/wiki/Power_of_g?action=edit&section=3
 44. http://vimdoc.sourceforge.net/cgi-bin/help?tag=:delete
 45. https://vim.fandom.com/wiki/Power_of_g?action=edit&section=4
 46. https://vim.fandom.com/wiki/Power_of_g?action=edit&section=5
 47. http://vimdoc.sourceforge.net/cgi-bin/help?tag=ex-cmd-index
 48. http://vimdoc.sourceforge.net/cgi-bin/help?tag=10.4
 49. http://vimdoc.sourceforge.net/cgi-bin/help?tag=multi-repeat
 50. https://vim.fandom.com/wiki/Power_of_g?action=edit&section=6
 51. https://vim.fandom.com/wiki/Power_of_g?oldid=40531
 52. https://vim.fandom.com/wiki/Special:Categories
 53. https://vim.fandom.com/wiki/Category:VimTip
 54. https://vim.fandom.com/wiki/Category:Searching
 55. https://www.fandom.com/licensing
 56. http://bit.ly/en-spotlight-fliplinestudiosfanon
 57. http://bit.ly/en-spotlight-xavierriddle
 58. http://bit.ly/en-spotlight-amphibia
 59. https://www.fandom.com/
 60. https://www.gamepedia.com/
 61. https://www.dndbeyond.com/
 62. https://www.muthead.com/
 63. https://www.futhead.com/
 64. https://www.fandom.com/about
 65. https://www.fandom.com/careers
 66. https://www.fandom.com/press
 67. https://www.fandom.com/about#contact
 68. https://www.fandom.com/terms-of-use
 69. https://www.fandom.com/privacy-policy
 70. https://community.fandom.com/Sitemap
 71. https://vim.fandom.com/wiki/Local_Sitemap
 72. https://community.fandom.com/wiki/Community_Central
 73. https://fandom.zendesk.com/
 74. https://community.fandom.com/wiki/Help:Contents
 75. https://www.fandom.com/do-not-sell-my-info
 76. https://www.fandom.com/mediakit
 77. https://www.fandom.com/mediakit#contact
 78. https://vim.fandom.com/wiki/Power_of_g
 79. http://bit.ly/31KuElR
 80. https://bit.ly/EndgameHT
 81. https://fandom.link/NeverSurrender

  Hidden links:
 83. https://www.fandom.com/
 84. https://www.fandom.com/
 85. https://www.facebook.com/getfandom
 86. https://twitter.com/getfandom
 87. https://www.youtube.com/fandomentertainment
 88. https://www.instagram.com/getfandom/
 89. https://www.linkedin.com/company/157252
 90. https://itunes.apple.com/us/app/fandom-videos-news-reviews/id1230063803?ls=1&mt=8
 91. https://play.google.com/store/apps/details?id=com.fandom.app&referrer=utm_source%3Dwikia%26utm_medium%3Dglobalfooter
 92. https://apps.apple.com/us/app/d-d-beyond/id1263629972
 93. https://play.google.com/store/apps/details?id=com.curse.dndbeyond&hl=en&referrer=utm_source%3Dwikia%26utm_medium%3Dglobalfooter
 94. https://vim.fandom.com/wiki/Power_of_g
 95. https://vim.fandom.com/wiki/Power_of_g