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
Table of contents 1 Review 2 Five strategies for ...
Original link https://github.com/XboxYan/no… A bu...
<div class="sideBar"> <div>...
Recently I changed Apache to nginx. When I moved ...
Preface When writing front-end pages, we often us...
This article records the installation tutorial of...
First time using docker to package and deploy ima...
Today I downloaded mysql-5.7.18-winx64.zip from t...
Data backup and restore part 3, details are as fo...
Application Scenario In many cases, we install so...
Mapping the mouse position or implementing drag e...
Table of contents Node connects to Mysql Install ...
How to create a virtual machine on VMware and ins...
There are two types of dead link formats defined b...
1. Install cmake 1. Unzip the cmake compressed pa...