Count File Statistics and Use Command History
In this step, you will learn how to use the wc command to count lines, words, and characters in files, and how to effectively use the command history feature in your terminal. Managing command history is crucial for efficiency and recalling previously executed commands.
First, let's explore the wc command (word count). This command is used to count the number of lines, words, and characters in a file.
Let's count the lines, words, and characters in the /etc/passwd file:
wc /etc/passwd
The output will show three numbers followed by the filename: lines, words, and characters. The exact numbers may vary slightly depending on your system configuration.
41 98 2338 /etc/passwd
You can use options to display only specific counts:
-l for lines
-w for words
-c for characters
Let's count only the lines in /etc/passwd and /etc/group (which contains information about user groups). We can do this on a single line using a semicolon.
wc -l /etc/passwd
wc -l /etc/group
You will see the line counts for each file:
41 /etc/passwd
63 /etc/group
Now, let's count only the characters in /etc/group and /etc/hosts (which maps hostnames to IP addresses).
wc -c /etc/group /etc/hosts
The output will show the character count for each file and a total count.
883 /etc/group
114 /etc/hosts
997 total
Next, we will learn about the command history. Your shell keeps a record of all commands you have executed. This is incredibly useful for re-running commands or remembering what you did previously.
To display your command history, use the history command:
history
You will see a numbered list of all commands you have entered in your current session and previous sessions. The output will vary greatly depending on your activity.
...output omitted...
23 clear
24 whoami
25 date
26 file /etc/passwd
27 cat /etc/passwd
28 head /etc/passwd
29 tail /etc/passwd
30 wc /etc/passwd
31 history
You can re-execute a command from your history using the exclamation point (!) followed by the command number or a string.
For example, to re-execute the command at number 26 (which was file /etc/passwd in the example above, but will be different for you), find its number in your history output and use it:
!26 ## Replace 26 with the actual number of 'file /etc/passwd' from your history
The shell will first display the command it's about to execute, then its output:
file /etc/passwd
/etc/passwd: ASCII text
You can also re-execute the most recent command that starts with a specific string. For instance, to re-run the last command that started with wc:
!wc
This will execute the last wc command you ran.
wc -c /etc/group /etc/hosts
883 /etc/group
114 /etc/hosts
997 total
These history features can significantly speed up your workflow by allowing you to quickly recall and re-execute complex commands without retyping them.