Friday, July 17, 2015

Vim tips on searching and replacing

This is not exhaustive or anything, just a memo.
's' means substitute. While it may also mean "search", the search command is usually a slash /, as in
/searchabletext
The simple of it:

:s/whatimlookingfor/whatshouldreplaceit

The slash separates the command, the searchable item, the replaceable item, and additional parameters.

To replace stuff throughout the whole file (or document), use the percent % sign before s:

:%s/whatimlookingfor/whatshouldreplaceit

:s/\&,/^M/g

This replaces commas across one (long or large) line with a newline (carriage return). Breakdown:

s/ — starts the substitute command
after slash, enter search string
\& — all occurrences of desired search string within a line
, — comma is what one is looking for
/ — the next slash separates the search string from the replacement
^M — newline (carriage return). in gVIM (for Windows), it's highlighted, as it's actually entered as <Ctrl+V> <enter>
/g — replace till the end of line. Useful for if there's a huge amount of text in one line.

If one wants carriage returns after a comma, use this:

:s/\&,/&^M/g
— where the usually coloured (and special) carriage return symbol ^M follows the ampersand &. The ampersand is used to to add text: stuff before it is added before the searchable string; stuff added after the ampersand means that instead of deleting, stuff is added after the searchable string.

Convenient.

:s/\&&quot\;/"/g

Here it replaces all &quot; with normal quote characters "
\& — all occurrences of search string within a line;
&quot\; note that the semicolon is escaped.

:s/\&description="/&\t

\& — search in a line all instances of
    description="
/
&\t — As stated above, the ampersand & is used to add stuff; in this instance, a tab \t is added after the searchable string.

Turn highlight off
Like this:nohlsearch
^ Given that all searchable strings found are highlighted. But then it becomes somewhat annoying when proceeding to edit text after things are done. Instructions from the Vim wikia.

Or:

:noh

16.04.2018:
Search for strings not containing a character (search with exclusions)

Search for a line not containing dots (periods):

/^[^\.]*$

Breakdown:

/ — starts a search
^ — start of a line
[^stuff_to_be_excluded] — exclusion [^inside square brackets, starting with caron]
[^\.] — the dot is escaped with a backslash \
* — wildcard for everything
$ — end of a line

Pressing enter/return will get you to the nearest match (if any), and highlight other matches. Move to the next match with the n key.

No comments: