当前位置:网站首页>Quickly master grep commands and regular expressions
Quickly master grep commands and regular expressions
2022-06-28 00:15:00 【Xianling Pavilion】
Built in support of extended regular expressions GNU edition grep Tools , be-all Linux All distributions are installed by default grep ,grep It is used to retrieve text information from any location on a server or workstation , How to be in Linux Systems and classes Unix Using regular expressions in our operating system grep Well ?
Learn about regular expressions quickly
1、 How to match what you're looking for ?
Regular expressions are just patterns that match each input line .
stay ‘/etc/passswd’ To retrieve the ‘vivek’ .
grep vivek /etc/passwd
Output result case :
vivek:x:1000:1000:Vivek Gite,,,:/home/vivek:/bin/bash
vivekgite:x:1001:1001::/home/vivekgite:/bin/sh
gitevivek:x:1002:1002::/home/gitevivek:/bin/sh
Search in any case ‘vivek’ ( It's not size sensitive ):
grep -i -w vivek /etc/passwd
Case insensitive Retrieval ‘vivek’ and ‘raj’ :
grep -E -i -w 'vivek|raj' /etc/passwd
In the last example , Using patterns that extend regular expressions .
Fixed location of retrieved content :
You can use ^ and $ Symbols force a regular expression to match the beginning or end of a line, respectively . The following example shows ‘vivek’ The opening text .
grep ^vivek /etc/passwd
Example of output results :
vivek:x:1000:1000:Vivek Gite,,,:/home/vivek:/bin/bash
vivekgite:x:1001:1001::/home/vivekgite:/bin/sh
You can just display with vivek The first line of text . For example, it doesn't show vivekgite , vivekg This is the beginning of the word .
grep -w ^vivek /etc/passwd
Search for ‘foo’ The text format at the end :
grep 'foo$' FILENAME
You can also search for blank lines in the following way :
grep '^$' FILENAME
2、 How to match specific characters ?
matching ‘Vivek’ or ‘vivek’ :
grep '[vV]ivek' FILENAME
Or you can :
grep '[vV][iI][Vv][Ee][kK]' FILENAME
You can match numbers ( For example, match vivek1 or Vivek2 ):
grep -w '[vV]ivek[0-9]' FILENAME
You can match two digits ( For example, match foo11 , foo12 ):
grep 'foo[0-9][0-9]' FILENAME
It's not just numbers , You can match letters :
grep '[A-Za-z]' FILENAME
Show all containing “w” or “n” Text lines of letters :
grep [wn] FILENAME
In the expression in brackets , stay “ [: ” and “ :] ” The name of the character class attached to : Represents a list of all characters belonging to the class . Standard character class name :
[:alnum:] – Alphanumeric character .
[:alpha:] – Alphabetical order
[:blank:] – Spaces and tabs .
[:digit:] – Numbers : ‘0 1 2 3 4 5 6 7 8 9’.
[:lower:] – Lowercase letters :‘a b c d e f ‘.
[:space:] – Special characters : tabs , A newline , Vertical tabs 、 Change the page , enter , And space .
[:upper:] – Capital :‘A B C D E F G H I J K L M N O P Q R S T U V W X Y Z’.
In the following example , Match all capital letters :
grep '[:upper:]' FILENAME
3、 How to use wildcards ?
You can use it. “.” Instead of a single character . In the following example , Checked all the letters with “b” start 、 Letter “t” The three character word at the end .
grep '\<b.t\>' FILENAME
In the example above :
\< Match the space string at the beginning of the word
\> Match the space string at the end of the word
Retrieve and output results for all two letters :
grep '^..$' FILENAME
Retrieve and display all information to ‘.’ And the result at the beginning of the number :
grep '^\.[0-9]' FILENAME
Escape character ’.’
The following regular expression looks for IP Address 192.168.1.254 The expected results will not be achieved :
grep '192.168.1.254' /etc/hosts
Three of these points need to be escaped :
grep '192\.168\.1\.254' /etc/hosts
The following example will match only one address :
egrep '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}' FILENAME
The following will match words regardless of case Linux or Unix :
egrep -i '^(linux|unix)' FILENAME
Explore in depth grep Advanced find mode
1、 How to retrieve a ‘-‘ The pattern of the beginning ?
Use -e Option to search for all matches ‘–test–‘ Result .grep Will try to put ‘–test–‘ As an option, parse :
grep -e '--test--' FILENAME
2、 How to be in grep Use in OR The logical operation of ?
grep -E 'word1|word2' FILENAME### OR ###egrep 'word1|word2' FILENAME
Or you can do it
grep 'word1\|word2' FILENAME
3、 How to be in grep Use in AND The logical operation of ?
Follow the syntax below to display all the included words ‘word1′ and ‘word2′ Result :
grep 'word1' FILENAME | grep 'word2'
Or you can :
grep 'foo.*bar\|word3.*word4' FILENAME
4、 How to test a sequence ?
You can use the following syntax to test the number of times a character repeats in a sequence :
{
N}
{
N,}
{
min,max}
The match contains two letters v The string result of :
egrep "v{2}" FILENAME
In the following example, the retrieval file contains “col” and “cool” The string result of :
egrep 'co{1,2}l' FILENAME
In the following example, the match will contain at least 3 Letters c Result :
egrep 'c{3,}' FILENAME
The following example will match “91-1234567890″ Mobile phone number in format ( namely “ Two digits - Ten digits ”)
grep "[[:digit:]]\{2\}[ -]\?[[:digit:]]\{10\}" FILENAME
5、 How to make grep Highlight the output of ?
Use the syntax of the following example :
grep --color regex FILENAME
6、 How to make grep The output of shows only the matching parts, not the whole line ?
Use the syntax of the following example :
grep -o regex FILENAME
Regular expression operators summary
Regular expressions : The operator meaning
. Match any single character .
? Match the previous character 0 Time or 1 Time .
* Match the previous character ≥0 Time .
+ Match the previous character ≥1 Time .
{
N} Match the previous character N Time .
{
N,} Match the previous character ≥m Time .
{
N,M} Match the previous character N To M Time .
– If the end point of a list or range in the list , Indicates the range .
^ Start marker , Indicates that an empty string is matched at the beginning . It also represents characters that are not in the range of the list .
$ End mark . Match an empty string .
\b Word lock . Match an empty string at the edge of a word .
\B Match an empty string at the non edge of a word .
\< Matches an empty string starting with a word .
\> Matches an empty string at the end of a word .
About grep and egrep
egrep namely grep -E , It interprets patterns as an extended regular expression .grep This is defined in the help document :
In basic regular expressions the meta-characters ?, +, {
, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{
,\|, \(, and \).
Traditional egrep did not support the {
meta-character, and some egrep implementations support \{
instead, so portable scripts should avoid {
in
grep -E patterns and should use [{
] to match a literal {
.
GNU grep -E attempts to support traditional usage by assuming that {
is not special if it would be the start of an invalid interval specification.
For example, the command grep -E '{1' searches for the two-character string {
1 instead of reporting a syntax error in the regular expression.
POSIX.2 allows this behavior as an extension, but portable scripts should avoid it.
The source code attachment has been packaged and uploaded to Baidu cloud , You can download it yourself ~
link : https://pan.baidu.com/s/14G-bpVthImHD4eosZUNSFA?pwd=yu27
Extraction code : yu27
Baidu cloud link is unstable , It may fail at any time , Let's keep it tight .
If Baidu cloud link fails , Please leave me a message , When I see it, I will update it in time ~
Open source address
Code cloud address :
http://github.crmeb.net/u/defu
Github Address :
http://github.crmeb.net/u/defu
come from “ ITPUB Blog ” , link :http://blog.itpub.net/69955379/viewspace-2900378/
边栏推荐
- 线程池实现:信号量也可以理解成小等待队列
- Character interception triplets of data warehouse: substrb, substr, substring
- How to use the apipost script - global variables
- Is the securities registration account safe? Is there any risk?
- mysql读写分离配置
- 炼金术(8): 开发和发布的并行
- Webserver flow chart -- understand the calling relationship between webserver modules
- golang使用mongo-driver操作——查(数组相关)
- 现代编程语言:zig
- How to use raspberry pie (and all kinds of pies)
猜你喜欢

翻译(5): 技术债务墻:一种让技术债务可见并可协商的方法

HCIP/HCIE Routing&Switching / Datacom备考宝典系列(十九)PKI知识点全面总结(公钥基础架构)
![Using two stacks to implement queues [two first in first out is first in first out]](/img/de/07297816f1a44d41389bb45d012c80.png)
Using two stacks to implement queues [two first in first out is first in first out]

logging日志的使用

Transmitting and receiving antenna pattern

零基础自学SQL课程 | SQL基本函数大全

安全省油环保 骆驼AGM启停电池魅力十足
![软件工程作业设计(1): [个人项目] 实现一个日志查看页面](/img/95/0c3f0dde16d220ddecb5758a4c31e7.png)
软件工程作业设计(1): [个人项目] 实现一个日志查看页面

赛尔笔记|视频文本预训练简述
![[paper reading | deep reading] sdne:structural deep network embedding](/img/6a/b2edf326f6e7ded83deb77219654aa.png)
[paper reading | deep reading] sdne:structural deep network embedding
随机推荐
现代编程语言:zig
技术的极限(11): 有趣的编程
mysql数据库旅游管理系统_JSP+MySQL基于ssm的旅游管理系统[通俗易懂]
Smart wind power | Tupu software digital twin wind turbine equipment, 3D visual intelligent operation and maintenance
MATLAB basic function length function
How to solve the problem that the browser developed with CeF3 does not support flash
智慧风电 | 图扑软件数字孪生风机设备,3D 可视化智能运维
Deployment and test of crtmp live video server
零基础自学SQL课程 | SQL中的日期函数大全
炼金术(9): 简约而不简单,永不停歇的测试 -- always_run
Storage structure of graph
Can you do these five steps of single cell data cleaning?
Is it safe for Huatai Securities to open an account online?
Although the TCGA database has 33 cancers
单片机之IIC通信协议「建议收藏」
一个人可以到几家证券公司开户?开户安全吗
[AI application] detailed parameters of NVIDIA geforce RTX 3060
Instructions for vivado FFT IP
SQL reported an unusual error, which confused the new interns
代码整洁之道--函数