Skip to content

Instantly share code, notes, and snippets.

@lsloan
Forked from sloanlance/Vim Notebook.md
Created July 13, 2017 15:42
Show Gist options
  • Select an option

  • Save lsloan/f80174cad3488c21186549ea95c928a4 to your computer and use it in GitHub Desktop.

Select an option

Save lsloan/f80174cad3488c21186549ea95c928a4 to your computer and use it in GitHub Desktop.
vim: Notes about using the vim editor, especially useful regular expressions (regex, regexes).

Vim Notebook

Notes about using the vim editor, especially useful regular expressions (regex, regexes).

  • Run an external command on all matching lines

    :g/pattern/.!command

    It's important that the dot command (.) appear between the search pattern and the bang (!) beginning the external command.

    For example, to run the rev shell command on every line that begins with the string "reverse":

    :g/^reverse/.!rev
    
  • Delete contiguous duplicate lines without sorting

    :g/^\(.*\)$\n\1$/d
    
  • Delete contiguous lines beginning with a hash (pound) sign

    :g/^\#.*$\n#/d
    

    This is similar to removing contiguous duplicate lines, except that the whole contents of the lines don't need to match, they only need to begin with #. This was helpful when editing a .bash_history file. Removing some commands from history left a lot of contiguous history timestamp comment lines, like #1499897624.

  • Delete non-contiguous duplicate lines without sorting

    :%!awk '\!a[$0]++'
    

    awk prints the first occurrence of each line by keeping an (associative) array of counters with the text of the line as the index. Whenever the counter for a line is zero (or unset), this expression evaluates to true, which causes awk to print it.

  • Collapse single-annotation PHPDoc comments

    :%s;^\(\s*/\*\*\)\n.*\* \(@.*\)\n.*\*/;\1 \2 */;
    

    For example, a PHPDoc like this:

    /**
     * @return bool
     */

    Becomes:

    /** @return bool */

    This helps save screen space, allowing more code to be seen at a time. It's great for declaring the return type of a function (as shown here) or the types of variables (with @var).

    This will probably work with document comments for other languages, too, like JavaDoc, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment