Sometimes you need to do things to the whole buffer. Instead of moving to the top, and then doing a dG to delete everything,you can issue global commands, based on line numbers:
syntax is
:line1,line2command |
Examples:
:1,20y |
:1,$d |
:%d |
Searching text is done with the command /xxx for a forwards search or ?yyy for a backwards search. n will skip to the next occurrence.When specifying / without argument vi will default to the argument of the last search.
Global Search and Replace:
The magic command is
:line1,line2s/old_string/new_string/g |
The /g is optional, it means 'do the replace everytime'.If not specified, vi will replace only the first occurrence in each line.
Special ^XX characters
To search for a ^XX character, you must use Ctrl-v (^v) in order to disable interpretation of the Ctrl commands.
A useful example:
Windows (MS-DOS) text files use RETURN/LINEFEED to end every line; Mac uses only RETURN; and Unix/Linux uses only NEWLINE (which is the same as the linefeed in DOS). To use the linux programming style:
\r\n = chr(13)chr(10) = MS-DOS
\r = chr(13) = Mac
\n = chr(10) = Linux/Unix
So when displaying an msdos ascii file with vi (or with any other text editor), you will find each and every line ended by a ^M (it's character 13, aka \r, aka ENTER). When displaying a mac ascii file, you will have a single line with a ^M at what should be each end of line.
Our MSDOS text file should look like this:
Friday the 13th^M ^M ^M ^M Dear Sir,^M ^M .... |
And our mac text file should look like that
"Friday the 13th^M^M^MDearSir,^M^M...." |
[The Macintosh->Unix conversion isn't easy to do with vi macros, so we'll concentrate on msdos/windows->Unix]
MS-DOS/Windows -> UNIX conversion:
In order to remove these ugly ^M, you search for them and replace them by....nothing!
So first, let's search for those weird ^M ... but, how can you search for character 'ENTER'?
By preceeding it with ^V (Control-V). Any keystroke after ^V is accepted literally -- that is, it won't have its usual command function, if it's something like ESC, ENTER, ^Z, etc...
What the following command tells VI to do is to replace the first (since the /g option isn't set, but anyway, we only expect one) ^M on every line, with nothing (there is nothing between the last two slashes: //):
This is what you type
:1,$s/^V^M// |
(where ^V is Control-V, and ^M is ENTER or Control-M)
note that VI doesn't display the ^V, so you'll only see
:1,$s/^M// |
This what you actually see
And it should work...
[FYI the "text-edition task force" is working on an elegant way to convert mac ascii files to unix, but the first research campaign hasn't brought us much]