Using cat, more, and less in the Linux Command Line
When working with text files in the Linux command line, three commonly used commands are cat, more, and less. Each of these commands has its own strengths and is suited for different tasks. This article will guide you through their usage with practical examples.1. cat - Concatenate and Display Files
The cat command is best suited for viewing shorter files. It reads files sequentially, writing them to standard output. For example, to view the contents of the /etc/fstab file, you can use:
Code:
cat /etc/fstab
This command will display the entire content of the /etc/fstab file on your terminal.
2. more - View File Contents Page by Page
For longer files, cat might not be the best option as the content can scroll by too quickly to read. Let's create a longer file using the dmesg command, which prints the kernel ring buffer messages, and redirect its output to a file:
Code:
sudo dmesg >> dmesg.txt
Now, if we try to view this file with cat:
Code:
cat dmesg.txt
The content will scroll by too fast to read. Instead, we can use the more command to view the file page by page:
Code:
more dmesg.txt
With more, you can scroll down using the down arrow key or the [space] key to go page by page. To quit, simply press [q]. However, if you try to scroll back up using the up arrow key, you'll find that more does not support backward navigation.
3. less - View File Contents with Bidirectional Scrolling
To overcome the limitation of more, we can use the less command, which allows both forward and backward navigation through the file:
Code:
less dmesg.txt
With less, you can use the down arrow key to scroll down, the up arrow key to scroll back up, and the [space] key to go page by page. To quit, press [q].
4. No Need to Combine cat with more or less
It's important to note that you don't need to combine more or less with cat. Both more and less can read files directly on their own. For example:
Code:
more /etc/fstab
Code:
less /etc/fstab
These commands will display the contents of the /etc/fstab file using more and less, respectively, without needing to use cat.
5. Combining more and less with Other Commands
more and less are not limited to text files; they can also be combined with other commands using pipes. For example, to view the output of the dmesg command with less, you can use:
Code:
sudo dmesg | less
This command will allow you to navigate through the dmesg output using less, providing the same bidirectional scrolling capabilities.
6. Cleaning Up
Finally, let's remove the test file we created:
Code:
rm dmesg.txt
This command will delete the dmesg.txt file from your system.
Last edited: