How Linux counts the number of specific characters in a file
This article is about how Linux counts the number of specific characters in a file. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Counting the number of a string in a file is actually looking for a stone in a piece of sand. after some people see the stone, make a grep on it, and then remember how many marks they have made; some people see the stone, dig it (tr), and finally count how many stones they have dug; some people see the stone, jump it (awk), and then count how many times they have jumped.
This is the file I used.
[root@bzhou test] # cat filehafsdfsdfsd
I want to match the string '''.
The-o option for 1.grep
[root@bzhou test] # grep-c '' file2
At the beginning, the option-c is used, but-c can only count one line, and if there are multiple matching strings in the line, then-c can do nothing.
This is correct.
[root@bzhou test] # grep-o '' file | wc-L3
2. Awk
This is thanks to blackold on CU.
[root@bzhou test] # awk-v RS='' 'END {print-- NR}' file
-v to set the value of a variable. RS is the delimiter of the record, and the default is the new line (\ n), which means that awk reads the data line by line, but now when RS is' ', press' ' to read the data, NR is the number of records read, and n records are separated by a NMAE delimiter, so it is-- NR.
3.tr
Strictly speaking, tr cannot match a string, only a single character. This matches the number of'h' in this file.
[root@bzhou test] # tr-cd'h'