MoonPoint Support Logo

 


Shop Amazon Warehouse Deals - Deep Discounts on Open-box and Used ProductsAmazon Warehouse Deals



Advanced Search
September
Sun Mon Tue Wed Thu Fri Sat
  3
       
2008
Months
Sep


Wed, Sep 03, 2008 6:27 pm

Remembering Text for a Regexp Replacement in Vi

I needed to insert a space between months and years in text in a document while using Vim, a version of the Vi editor for Windows systems. The text was as shown below:
December1999 Edition
November1999 Edition
October1999 Edition
...
March1996 Edition
February1996 Edition
January1996 Edition
With Vi, regular expressions can be used to search for and replace text. In this case I could use :.,$ s/199\(\d) Edition/ 199\1/ to perform the substitution.

To search from the line I was on to the end of the document I can use .,$. With the substitute s command, you can search and replace text with commands of the form s/old text/new text. You can use the i option, if you don't want the case of letters to be considered, i.e. if you wish "A" and "a" to be treated the same, then you can use s/old text/new text/i. You can use the g option, if you wish to replace all occurrences of old text on the line, for cases where the text may occur multiple times on the same line, e.g. s/old text/new text/g. You can use whatever delimiter you wish to separate the parts of the command, e.g. you can use s:old text:new text:.

The \d in the command indicates that I am only looking for digits, i.e. 0 to 9. By enclosing the \d in parentheses, i.e. by using (\d), I can have the editor "remember" whatever it found between the parentheses. Then I can have it insert what it has remembered in the replacement text by using \1. If I had used multiple parentheses at various parts in the search text, then the second string I wanted remembered would be indicated with a \2. In this case the last digit of the year was all I wanted the editor to remember and insert appropriately in the substitutiong text.

If you wish to search an entire document, you can use 1,$ to represent the first line of the file through the last line, or you can just use % to represent the entire file.

:% s/199\(\d) Edition/ 199\1/

References:

  1. Vim Regular Expressions - Substitute Command

[/software/editors/vi] permanent link

Once You Know, You Newegg AliExpress by Alibaba.com

Shop Amazon Local - Subscribe to Deals in Your Neighborhood

Valid HTML 4.01 Transitional

Privacy Policy   Contact

Blosxom logo