In this tutorial, we will be discussing how to edit a text file in Linux using the terminal. The three most common command-line text editors used in Linux are vi, nano, and emacs but we will be focusing on vi and nano for this post.
Editing a File using Vi Editor
vi is a standard text editor in Linux. To edit a file, you open the file using the vi editor and then switch to insertion mode. Let’s see how it’s done.
# Open a file vi filename.txt # Switch to insertion mode by pressing 'i' i # Edit the file as needed # Save changes and exit # Press 'Esc', type ':wq' and hit 'Enter' Esc :wq
Here, first, the vi editor is opened with the file. Then, by pressing ‘i’, you switch to the insertion mode that lets you edit the file. Once you’re done, press ‘Esc’ to switch back to command mode, type ‘:wq’ and hit ‘Enter’ to save and quit.
Editing a File using Nano Editor
nano is another text editor that is easier to use and has a more intuitive interface. Here’s how you can edit a file using nano:
# Open a file nano filename.txt # Edit the file as needed # Save changes and exit # Press 'Ctrl+X', press 'Y' to confirm changes, and then hit 'Enter' Ctrl+X Y Enter
First, open the file with nano. You can immediately begin editing. Once you’re done, press ‘Ctrl+X’ to exit. It will ask you whether or not you want to save the changes. Press ‘Y’ to confirm, and then ‘Enter’ to save and quit.
By mastering these commands, you can easily edit any text file right from your Linux terminal. It can be a faster and more efficient way to handle files on a Linux server.