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

  • https://stackoverflow.com/questions/25684559/what-is-the-difference-between-g-and-s-commands-in-vim

  • :g 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 there means global so it will replace all of them, 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 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).

你可能感兴趣的:(What is the difference between :g and :%s commands in vim)