Vim / Neovim Commands


Command :substitute (:s)

  1. Basic syntax: :[range]s/{pattern}/{replace}/[flags] [count]




Vim Commands on Files

  1. Commonly used ones:

  2. Symbol Meaning Example
    % The current file name :! echo % or :echo expand('%') gets main.c
    %:p Full absolute path of the current file :! echo %:p or :echo expand('%:p') gets /home/user/proj/src/main.c
    %:p:h Directory (head) of the current file :! echo %:p:h or :echo expand('%:p:h') gets /home/user/proj/src
    %:t Tail (basename only) :! echo %:t or :echo expand('%:t') gets main.c
    %:r Root (filename without extension) :! echo %:r or :echo expand('%:r') gets main
    %:e Extension name only :! echo %:e or :echo expand('%:e') gets c



Using External sed in Vim

  1. Basic syntax: :[range]!sed 's/{pattern}/{replace}/{flags}'


  2. Common use cases:

  3. Task Vim Command Equivalent Native Vim
    Simple substitution :%!sed 's/foo/bar/g' :%s/foo/bar/g (faster)
    Delete empty lines :%!sed '/^$/d' :g/^$/d (better)
    Delete lines with pattern :%!sed '/pattern/d' :g/pattern/d
    Print specific lines :%!sed -n '5,10p' :5,10 (view only)
    Insert line before match :%!sed '/pattern/i\New line' :g/pattern/norm! ONew line
    Append line after match :%!sed '/pattern/a\New line' :g/pattern/norm! oNew line
    Multiple operations :%!sed 's/a/A/g; s/b/B/g' :%s/a/A/g | %s/b/B/g
    Case conversion (uppercase) :%!sed 's/.*/\U&/' :% norm! gUU or :%s/.*/\U&/

  4. Advanced sed patterns:


  5. Practical examples:

  6. Description Command
    Filter current line through sed :.!sed 's/old/new/g'
    Filter visual selection :'<,'>!sed 's/old/new/g'
    Remove trailing whitespace :%!sed 's/[[:space:]]*$//'
    Number all lines :%!sed = | sed 'N;s/\n/\t/'
    Double-space document :%!sed G
    Delete HTML tags :%!sed 's/<[^>]*>//g'
    Convert DOS to Unix line endings :%!sed 's/\r$//'
    Swap first two fields (CSV) :%!sed -E 's/([^,]*),([^,]*)/\2,\1/'

  7. When to use sed vs native Vim commands:

  8. Use sed when... Use Vim's :s when...
    You need a specific sed script you already have Doing interactive editing (faster, better undo)
    Using complex sed-specific features Performance matters (no process spawning)
    Piping through multiple filters Need Vim registers or expression evaluation
    Combining with other Unix tools Working with visual selections frequently
    Testing sed script for shell use General text editing (native Vim is superior)

  9. Combining sed with other filters:


  10. Important note: In most cases, native Vim commands are preferred over external sed for better performance, undo granularity, and integration with Vim's features.