search
HomeWeb Front-endJS TutorialDetailed explanation of the use of regex and Linux's three major text processing tools

This time I will bring you a detailed explanation of the use of the three major text processing tools of Regex and Linux. What are the precautions when using the three major text processing tools of Regex and Linux. The following is a practical case. Let’s take a look. one time.

grep, sed and awk are all text processing tools. Although they are all text processing tools, they all have their own advantages and disadvantages. One text processing command cannot be completely replaced by another, otherwise it will not Three text processing commands appear.

1. Regular expression

1. Type of matching characters

[a-z]: Lowercase letters

[A-Z]: Uppercase letters

[a-Z]: Small or uppercase letters

[0-9]: Numbers

[a-zA-Z0-9]: Matches a character that is a letter or number

. : Matches any character, except spaces

[0-f] : Hexadecimal number

abc | def: abc or def
a (bc | de) f: abcf or adef

\<: the first word is usually preceded by a space or href="//m.sbmmt.com/m/wiki/88.html" target="_blank">Special characters are used as separators, and continuous strings are treated as words

\>: end of words

[^expression]: except lowercase letters All characters except , and so on.

2, followed by the following symbols to control the number of matches

The left side of such symbols must have the expression of the first point above

expression *: 0 or n characters

expression +: 1 or n characters

expression?: 0 or 1 character

expression {n}: n characters

Expression{n:m}:n to m characters

Expression{n,}:at least n characters

[Example][a-z] * means matching 0 or more lowercase letters

3. Control the matching characters at the beginning and end
^ Expression: The head matches

Expression$: The tail matches

2. Three major text processing tools in Linux

1. egrep filtering tool

Extension of grep version, you can use regular expressions

Syntax:

egrep -option 'regular expression' file name

Options:

-n: display lines No.
-o: Only display matching content
-q: Silent mode, no output, you have to use $? to determine whether the execution is successful, that is, whether the desired content is filtered
-l: If the match is successful, only the file name will be printed. If it fails, it will not be printed. Usually -rl is used together. grep -rl 'root' /etc
-A: If the match is successful, the matching line and the following n lines will be printed. Print them out together
-B: If the match is successful, print out the matching line and the n lines before and after it.
-C: If the match is successful, print out the matching line and the n lines before and after it.
--color
-c: If the match is successful, print out the number of matched lines
-i: Ignore case
-v: Negate, do not match
-w: Match words

2. sed streamEditor

Syntax:

Syntax 1: sed - option 'Number positioning + command' File name

Options:

-n: Silent mode, no output
-e: Multiple edits, this is not very clear
-i: Directly modify the file content, and Not output
-r: Extended mode, you can use regular expressions
-f: Specify the file name and write the action in a new file

Command:

a: Append,
c: Change,
d: Delete,
i: Insert, i can be followed by strings, and these strings will appear in a new line (the current previous line )
p: Print print
s: Replace substitute, you can directly perform the replacement work. Usually this s action can be paired with a regular expression. For example, 1,20s/old/new/g

*s command special instructions:

Use {Command 1: Command 2: Command 3} to add multiple commands

语法2:sed  -r  '替换命令s/正则表达式/替换内容/贪婪选项g'  文件名

定位的两种方法:

①数字定位(输入行序号定位)

十进制数
1:单行
1,3:范围 从第一行到第三行
2,+4:匹配行后若干行
4,~3:从第四行到下一个3的倍数行
2~3:第二行起每间隔三行的行
$:尾行
1!:除了第一行以外的行

【例】sed -n '1p' /etc/passwd

②正则表达式定位

正则必须用//包裹起来

扩展正则需要用 -r 参数或转义

替换可使用正则表达式的子模式,即小括号(),可以\1、\2代表子模式

【例】sed -r 's/(.)(.)/\2\1/ file1 表示将匹配到的第一部分和第二部分替换

*贪婪选项:填上g,代表把一行中所有匹配项替换

3、awk 文本分析工具

由命令、正则(需要用//包围起来)、比较和关系运算组合而成

使用option中的-F参数定义间隔符号

用$1,$2,$3等的顺序表示files中每行以间隔符号分隔的各列不同域,NF变量表示当前记录的字段数

语法

awk -选项 参数  '逻辑判断{命令 变量1,变量2,变量3}' 文件名

选项

-F 定义字段分隔符,默认的分隔符是连续的空格或制表符
-v 定义变量并赋值 也可以借用次方式从shell变量中引入

AWK变量

NR 当前记录的个数(全部文件连接后的统计)
FNR 当前记录的个数(仅为当前文件的统计,非全部)
FS 字段分隔符 默认为连续空格或制表符,可以使用多个不同的符号做分隔符 -F[:/]
OFS 输出字符的分隔符 默认是空格
# awk -F: 'OFS="=====" {print $1,$2}' /etc/passwd
root=====x
NF 当前读入行的字段个数
ORS 输出记录分隔符 默认是换行
# awk -F: 'ORS="=====" {print $1,$2}' /etc/passwd
root x=====bin x=====
FILENAME 当前文件名

【例1】使用AWK变量

# awk '{print NR,FNR,$1}' file1 file2 
1 1 aaaaa
2 2 bbbbb
3 3 ccccc
4 1 dddddd
5 2 eeeeee
6 3 ffffff
#

【例2】引用shell变量的方法

# a=root
# awk -v var=$a -F: '$1 == var {print $0}' /etc/passwd
或者 把整个命令拆开传递,让shell变量外露,
# awk -F: '$1 == "'$a'" {print $0}' /etc/passwd
# a=NF
# awk -F: '{print $'$a'}' /etc/passwd

逻辑运算(可直接引用域进行运算)

= += -= /= *= 赋值

&& || ! 逻辑与 逻辑或 逻辑非

~ !~  匹配正则或不匹配,正则需要用 /正则/ 包围住
>= != ==  关系 比较字符串时要把字符串用双引号引起来

$ 字段引用:字段引用需要加$,而变量引用直接用变量名

+ - * / % ++ --  运算符

转义序列

\\ \自身
\$ 转义$
\t 制表符
\b 退格符
\r 回车符
\n 换行符
\c 取消换行

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Linux grep与正则表达式的使用

怎么用正则把字符串分组

The above is the detailed content of Detailed explanation of the use of regex and Linux's three major text processing tools. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools