当前位置:网站首页>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/
边栏推荐
- 炼金术(7): 何以解忧,唯有重构
- Grab those duplicate genes
- Storage structure of graph
- TIME_ Solutions to excessive wait
- 本地可视化工具连接阿里云centOS服务器的redis
- 安全省油环保 骆驼AGM启停电池魅力十足
- QStringList 的学习笔记
- Does the subscription of Siyuan notes stop deleting cloud data directly?
- [黑苹果系列] M910x完美黑苹果系统安装教程 – 2 制作系统U盘-USB Creation
- Zero foundation self-study SQL course | complete collection of SQL basic functions
猜你喜欢

ASP.NET仓库进销存ERP管理系统源码 ERP小程序源码

Promise是什么

一文剖析C语言函数

An analysis of C language functions

夏日的晚会

Instructions for vivado FFT IP
![软件工程作业设计(1): [个人项目] 实现一个日志查看页面](/img/95/0c3f0dde16d220ddecb5758a4c31e7.png)
软件工程作业设计(1): [个人项目] 实现一个日志查看页面
![[try to hack] kill evaluation](/img/93/e623e25dc4dec1f656227c7651577e.png)
[try to hack] kill evaluation

Safe, fuel-efficient and environment-friendly camel AGM start stop battery is full of charm

Chenyun pytorch learning notes_ Build RESNET with 50 lines of code
随机推荐
用两个栈实现队列[两次先进后出便是先进先出]
技术的极限(11): 有趣的编程
自定义MySQL连接池
Zero foundation self-study SQL course | case function
零基础自学SQL课程 | IF函数
单片机之IIC通信协议「建议收藏」
炼金术(9): 简约而不简单,永不停歇的测试 -- always_run
Matlab基本函数 length函数
How to solve the problem that the browser developed with CeF3 does not support flash
Character interception triplets of data warehouse: substrb, substr, substring
代码整洁之道--格式
Pytorch Foundation (1)
Deployment and test of crtmp live video server
Msp430f5529 MCU reads gy-906 infrared temperature sensor
golang使用mongo-driver操作——查(数组相关)
[AI application] detailed parameters of NVIDIA Tesla v100s-pcie-32gb
100 questions for an enterprise architect interview
吴恩达《机器学习》课程总结(13)_聚类
QStringList 的学习笔记
MySQL分表查询之Merge存储引擎实现