23. Bash Shell - Text Processing: cat, tac, nl, head, tail
Contents
With word processing commands, we can easily get the text we want from a text output or text document.
Preparation
We can simply output a text to a file with the echo command.
Prepare contents:
|
|
Print text file contents from beginning with cat
We can use the cat command to view the text contents of the file from beginning:
|
|
Print text file contents from end with tac
We can use the cat command to view the text contents of the file from end:
|
|
Print contents and their line numbers with nl
We can use the nl command to display the text document content and the line number for each line of content:
|
|
Print the first lines of a text file with head
We can use the head command to output the beginning of the file contents:
|
|
Print the first twenty lines with parameter n
We can append a -n parameter to specify the number of rows to display
|
|
Print the last lines of a text file with tail
We can use the tail command to output the ending of the file contents:
|
|
Print the last twenty lines with parameter n
We can append a -n parameter to specify the number of rows to display
|
|
Print and interact text file content with more
We can use the more command to view and interact a text document’s contents:
|
|
Operations in less interactive mode
Some of the operations we can perform with the keyboard keys are:
Operation | Meaning |
---|---|
/string | Search for the string in the subsequent contents. |
:f | Show file name and current line number. |
B key | Beginning of the contents. |
Space key | Next page. |
Enter key | Next line. |
Q key | Quit interactive mode without showing the subsequent contents. |
Print and interact text file content with less
We can also use the less command to view and interact a text document’s contents:
|
|
Operations in more interactive mode
Some of the operations we can perform with the keyboard keys are:
Operation | Meaning |
---|---|
?string | Search for the string in the preceding contents. |
/string | Search for the string in the subsequent contents. |
Space key | Next page. |
Page Down key | Next page. |
Down key | Next line. |
Page Up key | Previous page. |
Up key | Previous line. |
Q key | Quit interactive mode without showing the subsequent contents. |
References 3.1 cat: Concatenate and write files, 3.2 tac: Concatenate and write files in reverse, 3.3 nl: Number lines and write files, 5.1 head: Output the first part of files, 5.2 tail: Output the last part of files, MORE(1), LESS(1)
Author Dong Chen
LastMod Sun Feb 24 2019