End of line characters

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...

Comments

Popular posts from this blog

Vim vi how to reload a file your editing