Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consistency in global operations in vim

Tags:

vim

sed

Consider these two vim commands

  1. :% s/one/two/g
  2. :% g/found/d

I am wondering why the g signaling global replacement and delete respectively needs to be put in the end in substitution and at the beginning in delete.

Do these follow a pattern that I am missing, or is this a vim corner case?

like image 640
Moeb Avatar asked Dec 16 '22 13:12

Moeb


1 Answers

I guess you are confused with :g[lobal], :s[ubstitute] and :[range]delete

let's make some example:

g is a flag of :s:

  • :s/foo/bar/ : replace only the first foo with bar in current line
  • :s/foo/bar/g : replace all foo with bar in current line
  • %:s/foo/bar/ : for each line in the whole file, replace only the first foo with bar
  • %:s/foo/bar/g : replace all foo with bar in whole file (all lines)

:g as :global command: :g can do with any commands, not only d

  • :g/foo/d : delete all matched lines default range is %
  • :%g/foo/d : same as above
  • :1,30g/foo/d: from line 1-30, remove all lines contain foo
  • :g/foo/normal >>: indent all lines, which match foo (not only work with d)
  • :g/foo/y A: yank all matched (/foo/) lines to register a (not only work with d)

:d command: (:[range]d[elete])

  • :/foo/d : /foo/ here is a range. delete next matched line
  • :%d : delete all lines (empty the file)
  • :%/foo/d : this won't work. because you have two ranges (% and /foo/)
  • :/foo/dg : this won't work either. no dg command
  • :g/foo/d : this works, same as above(the :g section), but it is from :global command

I hope you get a bit clear. (or more confused? I hope not.. ^_^)

you may want to take a look followings

:h :s
:h :g
:h :d
:h range
like image 200
Kent Avatar answered Dec 21 '22 09:12

Kent