250 CHAPTER 15 WORKING WITH TEXT FILES (1 on 1 web hosting)

250 CHAPTER 15 WORKING WITH TEXT FILES Note If you don t have the correct permissions to write a file, vi might tell you that you can use :w! to override. In this case, it s wrong. The only way to write to a file for which you don t have permissions is to change its permissions. Creating a New Text File Using vi Creating and editing a new file with vi is easy. From any command-line shell, simply type this: vi myfile This will start vi and give your new file a name. However, the file won t be saved until you manually issue the save command (:w) in vi. This means that if your computer crashes before you save, the file will be lost! Note The version of vi provided with Ubuntu, vim, includes some elementary file-save protection. If, for any reason, vim is not shut down properly, there s a chance you ll be able to recover a version of file the next time vim starts. However, as with all such protection in any kind of program, you shouldn t rely on this. You should use the :w command to save your file periodically. As always with vi, you start out in the default Command mode. To start typing immediately, enter Insert mode by typing i. You ll notice when typing that although the text is wrapped on each line, words are not carried over, and they often break across lines in an ugly way. This is because vi is primarily a text editor, not a word processor. For people who create text files, like programmers, having line breaks shown in this way can be useful. When you re finished typing a sentence or paragraph, you can press the Enter key as usual to start a new line. You should then be able to move between lines using the up and down cursor keys. You ll notice an odd thing when you try to do this, however: unlike with a word processor, moving up a line of text that spreads across more than one line on screen will take the cursor to the start of the line, rather than into the middle of it. This again relates to vi s text editor focus, where such a feature is useful when editing documents such as program configuration files. When you re finished, press the Esc key to switch to Command mode. Then type a colon to enter Command-Line mode. Type :w to save the file using the filename you gave it earlier. If you started vi without specifying a filename, you ll need to specify a filename with the save command, such as :w myfile.

Leave a Reply