Advanced Features of the cat Command
In this step, you will explore some additional useful features of the cat
command that can make working with text files more efficient.
Displaying Line Numbers
The cat
command can display line numbers for each line in a file using the -n
option:
## Navigate to the project directory if you're not already there
cd ~/project
## Display the complete message with line numbers
cat -n complete_message.txt
You should see output similar to:
1 This is the first part of the message.
2 Followed by the second segment.
3 And this concludes the third and final part.
4 Additional data transmission received.
5 End of transmission.
This feature is particularly useful when working with longer files where you need to reference specific lines.
Displaying Non-Printing Characters
Sometimes files may contain special or non-printing characters. The cat
command provides options to make these visible:
-T
: Displays tab characters as ^I
-v
: Shows non-printing characters
-E
: Displays a $
at the end of each line
Let's create a file with some special characters and then display it:
## Create a file with tabs and special characters
echo -e "Line with\ttab character\nAnother line" > special_chars.txt
## Display the file with special characters visible
cat -T special_chars.txt
Output:
Line with^Itab character
Another line
Now let's see the end-of-line characters:
## Display with end-of-line markers
cat -E special_chars.txt
Output:
Line with tab character$
Another line$
Creating Files Interactively
You can also use cat
to create files interactively. This is useful for creating small files without using a text editor:
## Create a new file interactively
cat > notes.txt
After executing this command, type the following lines:
Important notes:
1. Learn Linux commands
2. Practice file operations
3. Master redirection operators
When you're finished typing, press Ctrl+D
(which signals the end of input).
Let's verify the contents:
## Display the contents of the notes file
cat notes.txt
You should see:
Important notes:
1. Learn Linux commands
2. Practice file operations
3. Master redirection operators
Combining Multiple Features
You can combine multiple options to get the desired output:
## Show line numbers and end-of-line markers
cat -n -E notes.txt
Output:
1 Important notes:$
2 1. Learn Linux commands$
3 2. Practice file operations$
4 3. Master redirection operators$
These advanced features make the cat
command a versatile tool for working with text files in Linux.