Monday, December 26, 2011

vi tips

1) To convert a dos text file to unix file, in the escape mode of vi editor, type:

:set ff=unix

This removes the additional carriage return "\r" at the end of each line

2) To search and replace, in the escape mode:
:.,$s/pat1/pat2/g

This replaces pat1 by pat2 in all occurrences starting from the current position of the character to the end of the file. The current position indicated by . after : and end of the file is given by $ sign after the comma.

3) In command mode, to move to the beginning of the next line, type '+' and '-' to move to the starting of the previous line

4) To remove space from the beginning of all lines in vi editor:

:%s/^b\+//g

5) To replace a bunch of characters to newline in vi editor, use \r for searching.
For example, (1,2,3), ('a','b','c'), ('.....) : this list of tuples all printed in one line can be split as
(1,2,3)
('a','b','c')
....
by typing in escape mode in vi editor:

:%s/), /\r/g

Note the space following ), characters. Note also that there is no need to escape \ in \r.

5) So, during the initial days of my cooking, I used to just  copy and paste the recipes from web to my editor. This editor was Notepad during my W7 days and when I installed Mint 16, I naturally switched to vi. Because of this transition, I started seeing a lot of Windows specific metacharacters in the recipe file. They look like this: <96> or <97>. You cannot search for this combination of characters as they are not separate. For this, I found the solution from SuperUser by this user

:%s/[\x96]//g

This syntax deletes all the occurrences. You can add additional characters as follows:

:%s/[\x96\x97]//g

It is important to have \x in the syntax to indicate you are searching for special characters in their hex code. If you know the exact equivalent character you may add it in the 'replace' part of the command.

No comments:

Post a Comment