Detailed commands and codes of regular expressions in Linux (with experimental notes)

Regular expression

One, sort command

Sort the contents of the files by row, or according to different data types

(1) Syntax format:

sort [选项] 参数

常用选项:
-f:忽略大小写
-b:忽略每行前面的空格
-M:按照三字符月份进行排序
-n:按照数字进行排序
-r:反向排序
-u:等同于uniq,表示相同的数据仅显示一行
-t:指定字段分隔符,默认使用[Tab]键分隔
-k:指定排序字段
-o [输出文件]:将排序后的结果转存至指定文件

Example:

sort -n testfile2

Insert picture description here

sort -t ':' -k 3 -n /etc/passwd

Insert picture description here

du -ah | sort -nr -o du.txt

Insert picture description here

Two, uniq command

Syntax format:

uniq [选项] 参数

常用选项:
-c:进行计数,并删除文件中重复出现的行
-d:仅显示重复行
-u:仅显示出现一次的行

Three, tr command

语法格式:
tr [选项] [参数]

常用选项:
-c:保留字符集1的字符,其他的字符用(包括换行符\n)字符集2替换
-d:删除所有属于字符集1的字符
-s:将重复出现的字符串压缩为一个字符串;用字符集2 替换 字符集1
-t:字符集2 替换 字符集1,不加选项同结果。

字符集1:指定要转换或删除的原字符集。
字符集2:指定要转换成的目标字符集。	

Delete blank lines

echo -e "aa\n\n\n\n\nbb" | tr -s "\n"

Insert picture description here
Replace the colon ":" in the path variable with a newline character "\n"

echo $PATH | tr -s ":" "\n"

Insert picture description here

(1) Common metacharacters in basic regular expressions

Supported command tools: grep, egrep, sed, awk

\ :转义字符,用于取消特殊符号的含义
例:\!、\n、\$等

^ :匹配字符串开始的位置,
例:^a、^the、^#、^[a-z] 

$ :匹配字符串结束的位置
例:word$、^$匹配空行

. :匹配除\n之外的任意的一个字符
例:go.d、g..d

* :匹配前面子表达式0次或者多次
例:goo*d、go.*d

[list] :匹配list列表中的一个字符
例:go[ola]d,[abc]、[a-z]、[a-z0-9]、[0-9]匹配任意一位数字

[^list] :匹配任意非list列表中的一个字符,
例:[^0-9]、[^A-Z0-9]、[^a-z]匹配任意一位非小写字母

\{n\} :匹配前面的子表达式n次,
例:go\{2\}d、'[0-9]\{2\}'匹配两位数字

\{n,\} :匹配前面的子表达式不少于n次,
例:go\{2,\}d、'[0-9]\{2,\}'匹配两位及两位以上数字

\{n,m\} :匹配前面的子表达式n到m次,
例:go\{2,3\}d、'[0-9]\{2,3\}'匹配两位到三位数字
注:egrep、awk使用{n}、{n,}、{n,m}匹配时“{}”前不用加“\”

(2) Extended regular expression metacharacters

Supported command tools: egrep, awk

+ :匹配前面子表达式1次以上
例:go+d,将匹配至少一个o,如god、good、goood等

? :匹配前面子表达式0次或者1次
例:go?d,将匹配gd或god

() :将括号中的字符串作为一个整体
例:g(oo)+d,将匹配oo整体1次以上,如good、gooood等

| :以或的方式匹配字条串
例:g(oo|la)d,将匹配good或者glad

Example: regular expression matching E-mail address

邮箱可以分为三部分:
用户名@ :
^([a-zA-Z0-9_\-\.\+]+)@

子域名 :
([a-zA-Z0-9_\-\.]+)

.顶级域名 :
\.([a-zA-Z]\{2,5\})$

用awk和egreap都可以进行操作,就是格式不同

egrep:

egrep '^([a-zA-Z0-9_\-\.\+]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$' email.txt

Insert picture description here
awk:

awk '/^([a-zA-Z0-9_\-\.\+]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/{print $0}' email.txt

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51468875/article/details/111690205