How do i use regular expressions with vi?



  • A lot of this applies to vim also, most recent linux OS's will call vim.

    Man page for vim: https://www.lightnetics.com/post/3435
    Link to regular expressions: https://www.lightnetics.com/post/3348
    Vim documentation on substitution: http://vimdoc.sourceforge.net/htmldoc/usr_10.html#10.2
    Vim documentation on patterns: http://vimdoc.sourceforge.net/htmldoc/usr_27.html

    The format of the regular expression when you presss colon in vi.

    :

    The format of the command is:

    :[range]s[ubstitute]/pattern/string/[options]

    Explaining each section.

    The range are the line you want to target for changes.

    The Range

    . The dot means current line.

    $ The dollar means last line.

    * The visual area.

    % The entire file.

    'c The position of the mark c.

    /{pattern}[/] The next line which matches the pattern.

    ?{pattern}[?] The previous line which matches the pattern.

    & The next line where the previous substitution matches.

    ? The previous line where the previous substitution matches.

    / The next line where the previously used search matches.

    The above can be used with with + and - (plus/minus) followed by an optional number, the default number is 1, if not provided. These symbols mean add or subtract to the preceding line match.

    The s[ubstitute]

    Means you are using the substutute option for text manipulation.

    /pattern/

    Means the what you are searching for in the file.

    /string/

    Means what you want the pattern to change to.

    /options

    Specify additional options.

    Examples.

    Sample file:

    &lt!DOCTYPE html&gt
    &lthtml&gt
    &ltbody&gt
    
      &lth1>My First Heading&lt/h1&gt
      &lth1>My Second Heading&lt/h1&gt
      &ltp>My first paragraph.&lt/p&gt
    
    &lt/body&gt
    &lt/html&gt
    

    g - Replace all occurrences in the line (without g - only first).

    Change h1 to h2 only on line 5, ever occurrence on that line.

    :5s/h1/h2/g

    Same as above but confirming every change. Useful for testing.

    :5s/h1/h2/cg

    replace with h1 (y/n/a/q/l/^E/^Y)?
    At this point, you must enter one of the following answers:

    y		Yes; make this change.
    n		No; skip this match.
    a		All; make this change and all remaining ones without further confirmation.
    q		Quit; don't make any more changes.
    l		Last; make this change and then quit.
    CTRL-E		Scroll the text one line up.
    CTRL-Y		Scroll the text one line down.
    

    Change all h1 tags to h2 tags in the entire file.

    %s/h1/h2/g



© Lightnetics 2024