In Ubuntu and other Linux distributions, the command line interface (CLI) can perform various tasks. One common task that users often encounter is editing files directly from the command line. In this Answer, we’ll explore several methods for editing files on the command line in Ubuntu.
Throughout this Answer, we’ll edit the file example.txt
provided in the code below:
Placeholder text
We can run each command we encounter later inside this widget to see how this file changes. We’ll use the following command to check the content of the example.txt
file:
cat example.txt
We can use the nano
command to edit files on the command line. Enter this command in the terminal above:
nano example.txt
Nano opens the file in the terminal window, allowing us to make changes using keyboard shortcuts. Once we’re done editing, press Ctrl + X
to exit Nano, and we’ll be prompted to save our changes before closing. After making our changes, check the new contents of the file with the command provided prior.
To edit the file with vim
, enter the following command:
vim example.txt
This will open the Vim editor. Vim has different modes for navigating and editing text, and is quite complex to understand. To start editing, press i
to enter insert mode, make changes, and then press Ctrl + C
to return to normal mode. To save the changes and exit Vim, type :wq
and press Enter
. After making our changes, check the new contents of the file with the command provided prior.
We can use echo
to make edits without opening a text editing interface. For example, to append a line of text to a file, we can use the following command:
echo "new line of text" >> example.txt
After making our changes, check the new contents of the file with the command provided prior.
To create a new file or overwrite an existing file, we can use the following command:
cat > example.txt
Note: With this
cat
command, whatever text we enter will overwrite the entire content of the target file, instead of appending it.
After making our changes, check the new contents of the file with the command provided prior.
Free Resources