How can I edit a file in Linux?
Editing a file is normal as well as essential. We often have to edit files on our computers and servers. It doesn’t matter whether it is a CSV file, a text file or a configuration file. If you are just getting started with Linux, it can be a tough task to learn how to edit a file in Linux. So, in this tutorial, I will show you how to edit a file in Linux.
To edit a file in Linux, you must know the location of a file you want to edit. Once you know the location, you can open and edit it in your favorite text editor. If you do not have a favorite text editor yet, I recommend you to get started with
nano editor. Nano editor is the easiest.
So, Let’s assume that we have multiple files in our home directory. To get a list of files and directories in the current directory, execute the following command.
Now, execute the following command to open a specific file in the nano editor in edit mode.
$ nano FILE_NAME
Just like any other text editor, you can move your pointer using arrow keys and you can edit a file as you want. Once you are done editing, press CTRL+X followed by Y followed by the Enter key to save your file.
After editing, if you do not want to save changes, press CTRL+X followed by N followed by Enter.
This is how you can edit a file located in the current directory. But what if it is located in a different directory? You can use the absolute path of a file you want to edit. For example, If you want to edit a file that is located in
/etc/apache2 directory, you can use the following command.
$ sudo nano /etc/apache2/FILE_NAME
Do not forget to replace a FILE_NAME placeholder with the actual file name. As we are using the absolute path of the file, we can run this command anywhere on the system.
If you want to edit multiple files with the same extension, you can take advantage of wildcard characters in Linux. Let’s assume that we want to edit all the files with
.csv extension in the current directory. In this case, the command would be.
$ sudo nano *.conf
Similarly, if you want to edit all the files starting with A, you can execute the following command.
$ sudo nano A*
It will give you one file at a time to edit. You can edit one file after another as per your requirements. If you want to skip a specific file, You can just press CTRL+X.
So, this is how you can edit files in Linux. There are many other text editors in Linux like Vi, Vim and Pico. You can use the one that suits you the best. To replace some text in your files, you can use sed command in linux. If you want to know more about editing files in Linux, please let us know in the comment section given below, we are happy to help!