Jan 03

Regex Search Lines Add Quotes

Regex to search a whole file and if the line contains the search word, add beginning and ending quotes. I in this case doing it vi(m).

This works to add beginning and ending quotes to ALL lines in the file

**:%s/^(.*)$/\\1/**

or simpler

**:%s/.*/&**

Explanation:

By default, a pattern is interpreted as the largest possible match, so .* is interpreted as the whole line, with no need for ^ and $. And while (…) can be useful in selecting a part of a pattern, it is not needed for the whole pattern, which is represented by & in the substitution. And the final / in a search or substitution is not needed unless something else follows

However we do NOT want all lines in the file only the lines containing the search word.

This works. I am not sure if this is reliable without using anchors ^ and $ but it seems to work in my limited test.

**:%s/.*mysearchword.*/&**

Comments Off on Regex Search Lines Add Quotes
comments

Comments are closed.