Showing posts with label VI. Show all posts
Showing posts with label VI. Show all posts

Wednesday, January 23, 2008

VI editor: Search and Replace text

IMPORTANT! Before start changing your text file, please remember the commands to UNDO and REDO:


:u or :undo[n]
:red or :redo[n]

where "n" is the number of changes. The default value is "n=1".


With the command (in ESC mode):

:%s/foo/bar/gc

the active file will be searched for the pattern "foo" and replaced with "bar". For every replacement you'll be asked for a confirmation.

With

:%s/foo/bar/g

you won't be asked for a confirmation.

:%s/foo/bar/gi is case-insensitive
:%s/foo/bar/gI is case-sensitive

With ESC or "q" you terminate the searching.

Note that above we used the % symbol. This is a shortcut that means "from the first line to the end of file".

The "substitute" (:s) command accepts, before of itself, a range of lines, e.g.:


:28s/text1/text2/ only on line 28
:.s/text1/text2/ only on the current line
:.,20s/text1/text2/ from current to line 20
:1,$s/text1/text2/ from line 1 to the end of file
:%s/text1/text2/ over the whole file. Like 1,$


Morevore please notice that if you want to use special characters like [ you have to escape them, like:


:.,$s/lego/\[lego/gc


this command substitutes all the occurrences of "lego" with "[lego", from the current line to the end of file, asking for confirmation before each substitution.

IMPORTANT. Please notice that you have to escape symbols ONLY within the substituting text, not in the text you look for. E.g.:

:.,$s/(ciao)/\[\(ciao)\)\]/gc

substitutes "(ciao)" with "[(ciao)]".

Wednesday, January 9, 2008

VI editor: comment a whole line or N lines

If you want to comment N lines of a Bash script (for example) with the VI (or VIM) editor you have to type in ESC- mode (type ESC before typing the command):


:.,25s/^/# /

where ".,25s" stands for "from the current line to line number 25" and the sequence added to comment a line is "# " (hash plus a white space).
For a single line:

:11s/^/# /

for the 11th line or

:.s/^/# /

for the current line pointed by the cursor.



To uncomment:

:1,$s/^# //

where "$" stands for "last line", i.e. "from line 1 to the end of file".

Friday, May 4, 2007

How to safely use backspace with VI editor under linux?

Sometimes, when you log on a linux machine and try to edit a file with VI editor, you get characters like '?>' when you click on backspace in order to delete a string. How to fix it?

Solution:

In your HOME directory (if you don't know where is it, just type 'cd' at the prompt) edit your .bashrc (or your .bash_profile) file and add these lines:

#Let VI work with Backspace
echo "I run 'stty sane'"
stty sane
echo "Done"

The .bashrc file is loaded (and sourced) every time you log in the machine or you start a shell; so your VI will properly work for ever since now on! : )

P.S. I like to know what my .bashrc does, but if you prefer you can delete the echo lines, of course.