Counting the number of a string in a file is actually like looking for stones in a piece of sand. Some people make a mark on the stone after seeing it (grep), and then remember how many marks they made; some people dig it up after seeing the stone (tr), and finally count how many stones they dug; some people jump over the stone after seeing it (awk), and then count how many times they jumped. This is the file I used [root@bzhou test]# cat file hafsdha hahafsdfsdhaha haha I want to match the string 'haha' 1. Grep's -o option [root@bzhou test]# grep -c 'haha' file 2 At the beginning, the -c option was used, but -c can only count one line. If there are multiple matching strings in a line, -c will be powerless. This is correct [root@bzhou test]# grep -o 'haha' file | wc -l 3 2. awk This thing is thanks to blackold on CU. [root@bzhou test]# awk -v RS='haha' 'END {print --NR}' file -v is used to set the value of a variable. RS is the record separator. The default is new line (\n), which means that awk reads data line by line. But now when RS is 'haha', it reads data as 'haha'. NR is the number of records read. n records are separated by n-1 separators, so it is --NR. 3.tr Strictly speaking, tr cannot match strings, it can only match single characters. Here we match the number of 'h' in this file. [root@bzhou test]# tr -cd 'h' <file | wc -c 8 [root@bzhou test]# grep -o 'h' file | wc -l 8 -d can delete a certain character. If only -d is used, the string after deleting the specific character will be output. However, -c can reverse the display, which means that the deleted characters are displayed. Then you can use wc -c to count the number of characters. Summarize The above is the full content of this article. I hope that the content of this article will have certain reference learning value for your study or work. Thank you for your support of 123WORDPRESS.COM. If you want to learn more about this, please check out the following links You may also be interested in:
|
<<: How to query and update the same table in MySQL database at the same time
>>: Summary of commonly used operators and functions in MySQL
Today I made a menu button. When you move the mous...
1. Packetdrill compilation and installation Sourc...
This article uses an example to describe the mana...
I am writing a small program recently. Because th...
DOCTYPE DECLARATION At the top of every page you w...
Sometimes we need to remotely run programs on the...
I designed and customized a navigation bar with a...
Table of contents The role of cloneElement Usage ...
cause The way to import external files into a min...
This article describes the MySQL data types and f...
1. Use version vite:2.0 ant-design-vue: 2.0.0-rc....
In the horizontal direction, you can set the alig...
1. Introduction Supervisor is a general process m...
As shown below, if it were you, how would you ach...
Table of contents 1. Introduction: 2. The first i...