04 Shell编程之正则表达式与文本处理器

目录

[4.1 正则表达式](#4.1 正则表达式)

[4.1.1 正则表达式概述](#4.1.1 正则表达式概述)

[1. 正则表达式的定义](#1. 正则表达式的定义)

[2. 正则表达式用途](#2. 正则表达式用途)

[4.1.2 基础正则表达式](#4.1.2 基础正则表达式)

[1. 基础正则表达式示例](#1. 基础正则表达式示例)

[1. 查找特点字符](#1. 查找特点字符)

[2. 利用中括号"[]"来查找集合字符](#2. 利用中括号"[]"来查找集合字符)

[3. 查找行首"^"与行尾字符""](#3. 查找行首"^"与行尾字符"")

[4. 查找任意一个字符"."与重复字符"*"](#4. 查找任意一个字符"."与重复字符"*")

[5. 查找连续字符范围"{}"](#5. 查找连续字符范围"{}")

[2. 元字符总结](#2. 元字符总结)

[4.1.3 扩展正则表达式](#4.1.3 扩展正则表达式)

[4.2 文本处理器](#4.2 文本处理器)

[4.2.1 sed工具](#4.2.1 sed工具)

[1. sed命令常见用法](#1. sed命令常见用法)

[2. 用法示例](#2. 用法示例)

[1. 输出符合条件的文本(p表示正常输出)](#1. 输出符合条件的文本(p表示正常输出))

[2. 删除符合条件的文本(d)](#2. 删除符合条件的文本(d))

[3. 替换符合条件的文本](#3. 替换符合条件的文本)

[4. 迁移符合条件的文本](#4. 迁移符合条件的文本)

[5. 使用脚本编辑文件](#5. 使用脚本编辑文件)

[6. sed直接操作文件示例](#6. sed直接操作文件示例)

[4.2.2 awk工具](#4.2.2 awk工具)

[1. awk常见用法](#1. awk常见用法)

[2. 用法示例](#2. 用法示例)

[1. 按行输出文本](#1. 按行输出文本)

[2. 按字段输出文本](#2. 按字段输出文本)

[3. 通过管道、双引号调用Shell命令](#3. 通过管道、双引号调用Shell命令)

[4.2.3 sort 工具](#4.2.3 sort 工具)

[4.2.4 uniq 工具](#4.2.4 uniq 工具)

[4.2.5 tr 工具](#4.2.5 tr 工具)


4.1 正则表达式

4.1.1 正则表达式概述

1. 正则表达式的定义

正则表达式又称正规表达式、常规表达式。在代码中常简写为regex、regexp或RE。正则表达式是使用单个字符串来描述、匹配一系列符合某个句法规则的字符串,简单来说,是一种匹配字符串的方法,通过一些特殊符号,实现快速查找、删除、替换某个特定字符串。

正则表达式是由普通字符与元字符组成的文字模式。模式用于描述在搜索文本时要匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。其中普通字符包括大小写字母、数字、标点符号及一些其他符号,元字符则是指那些在正则表达式中具有特殊意义的专用字符,可以用来规定其前导字符(即位于元字符前面的字符)在目标对象中的出现模式。

正则表达式一般用于脚本编程与文本编辑器中。很多文本处理器与程序设计语言均支持正则表达式,例如 Linux系统中常见的文本处理器(grep、egrep、sed、awk)以及应用比较广泛的Python语言。正则表达式具备很强大的文本匹配功能,能够在文本海洋中快速高效地处理文本。

2. 正则表达式用途

对于一般计算机用户来说,由于使用到正则表达式的机会不多,所以无法体会正则表达式的魅力,而对于系统管理员来说,正则表达式则是必备技能之一。

正则表达式对于系统管理员来说是非常重要的,系统运行过程中会产生大量的信息,这些信息有些是非常重要的,有些则仅是告知的信息。身为系统管理员如果直接看这么多的信息数据,无法快速定位到重要的信息,如"用户账号登录失败""服务启动失败"等信息。这时可以通过正则表达式快速提取"有问题"的信息。如此一来,可以将运维工作变得更加简单、方便。

目前很多软件也支持正则表达式,最常见的就是邮件服务器。在Internet中,垃圾I广告邮件经常会造成网络塞车,如果在服务器端就将这些问题邮件提前剔除的话,客户端就会减少很多不必要的带宽消耗。而目前常用的邮件服务器postfix 以及支持邮件服务器的相关分析软件都支持正则表达式的对比功能。将来信的标题、内容与特殊字符串进行对比,发现问题邮件就过滤掉。

除邮件服务器之外,很多服务器软件都支持正则表达式。虽然这些软件都支持正则表达式,不过字符串的对比规则还需要系统管理员来添加,因此正则表达式是系统管理员必须掌握的技能之一。

4.1.2 基础正则表达式

正则表达式的字符串表达方法根据不同的严谨程度与功能分为基本正则表达式与扩展正则表达式。基础正则表达式是常用正则表达式最基础的部分。在 Linux系统中常见的文件处理工具中 grep 与 sed支持基础正则表达式,而 egrep 与 awk支持扩展正则表达式。掌握基础正则表达式的使用方法,首先必须了解基本正则表达式所包含元字符的含义,下面通过grep命令以举例的方式逐个介绍。

1. 基础正则表达式示例

下面的操作需要提前准备一个名为test.txt 的测试文件,文件具体内容如下所示。

[root@localhost ~]# vim test.txt 
he was short and fat.
he was weating a blue polo shirt with black pants.
The home of Football on BBC Sport online.
the tongue is boneless but it breaks bones.12!
google is the best tools for search keyword.
PI=3.14
a wood cross!
Actions speak louder than words

#woood #
#woooooooood #
AxyzxyzxyzxyzC
I bet this place is really spooky late at night!
Misfortunes never come alone/single.
I shouldn't have lett so tast.
1. 查找特点字符

查找特定字符非常简单,如执行以下命令即可从test.txt文件中查找出特定字符"the"所在位置。其中"-n"表示显示行号、"-i"表示不区分大小写。命令执行后,符合匹配标准的字符,字体颜色会变为红色。

[root@localhost ~]# grep -n 'the' test.txt 
4:the tongue is boneless but it breaks bones.12!
5:google is the best tools for search keyword.
[root@localhost ~]# grep -in 'the' test.txt 
3:The home of Football on BBC Sport online.
4:the tongue is boneless but it breaks bones.12!
5:google is the best tools for search keyword.
[root@localhost ~]# 

若反向选择,如查找不包含"the"字符的行,则需要通过grep命令的""-v"选项实现,并配合"-n"一起使用显示行号。

[root@localhost ~]# grep -vn 'the' test.txt 
1:he was short and fat.
2:he was weating a blue polo shirt with black pants.
3:The home of Football on BBC Sport online.
6:PI=3.14
7:a wood cross!
8:Actions speak louder than words
9:
10:#woood #
11:#woooooooood #
12:AxyzxyzxyzxyzC
13:I bet this place is really spooky late at night!
14:Misfortunes never come alone/single.
15:I shouldn't have lett so tast.
16:
[root@localhost ~]# 
2. 利用中括号"[]"来查找集合字符

想要查找"shirt"与"short"这两个字符串时,可以发现这两个字符串均包含"sh"与"rt"。此时执行以下命令即可同时查找到"shirt"与"short"这两个字符串,其中T中无论有几个字符,都仅代表一个字符,也就是说"[io]"表示匹配"i"或者"o"。

[root@localhost ~]# grep -n 'sh[io]rt' test.txt 
1:he was short and fat.
2:he was weating a blue polo shirt with black pants.
[root@localhost ~]# 

若要查找包含重复单个字符"oo"时,只需要执行以下命令即可。

[root@localhost ~]# grep -n 'oo' test.txt 
3:The home of Football on BBC Sport online.
5:google is the best tools for search keyword.
7:a wood cross!
10:#woood #
11:#woooooooood #
13:I bet this place is really spooky late at night!
[root@localhost ~]# 

若查找"oo"前面不是"w"的字符串,只需要通过集合字符的反向选择[T"来实现该目的。例如执行"grep -n'[w]oo'test.txt"命令表示在test.txt文本中查找"oo"前面不是"w"的字符串。

[root@localhost ~]# grep -n '[^w]oo' test.txt 
3:The home of Football on BBC Sport online.
5:google is the best tools for search keyword.
10:#woood #
11:#woooooooood #
13:I bet this place is really spooky late at night!
[root@localhost ~]# 

在上述命令的执行结果中发现"woood"与"wooooood"也符合匹配规则,二者均包含"w""。其实通过执行结果就可以看出,符合匹配标准的字符加粗显示,而上述结果中可以得知,"#woood #"中加粗显示的是"ooo",而"oo"前面的""o"是符合匹配规则的。同理"#woooooood #"也符合匹配规则。

若不希望"oo"前面存在小写字母,可以使用"grep -n'[^a-z]oo'test.txt"命令实现,其中"a-z"表示小写字母,大写字母则通过"A-Z"表示

[root@localhost ~]# grep -n '[^a-z]oo' test.txt 
3:The home of Football on BBC Sport online.
[root@localhost ~]# 

查找包含数字的行可以通过"grep -n[O-9]'test.txt"命令来实现。

[root@localhost ~]# grep -n '[0-9]' test.txt 
4:the tongue is boneless but it breaks bones.12!
6:PI=3.14
[root@localhost ~]# 
3. 查找行首"^"与行尾字符"$"

基础正则表达式包含两个定位元字符:"^"(行首)与"$"(行尾)。在上面的示例中,查询"the"字符串时出现了很多包含"the"的行,如果想要查询以"the"字符串为行首的行,则可以通过"^"元字符来实现。

[root@localhost ~]# grep -n '^the' test.txt 
4:the tongue is boneless but it breaks bones.12!
[root@localhost ~]# 

查询以小写字母开头的行可以通过"^[a-z]"规则来过滤,查询大写字母开头的行则使用"^[A-Z]"规则,若查询不以字母开头的行则使用[^a-zA-Z]"规则。

[root@localhost ~]# grep -n '^[A-Z]' test.txt 
3:The home of Football on BBC Sport online.
6:PI=3.14
8:Actions speak louder than words
12:AxyzxyzxyzxyzC
13:I bet this place is really spooky late at night!
14:Misfortunes never come alone/single.
15:I shouldn't have lett so tast.
[root@localhost ~]# grep -n '^[a-z]' test.txt 
1:he was short and fat.
2:he was weating a blue polo shirt with black pants.
4:the tongue is boneless but it breaks bones.12!
5:google is the best tools for search keyword.
7:a wood cross!
[root@localhost ~]# grep -n '^[^a-zA-Z]' test.txt 
10:#woood #
11:#woooooooood #
[root@localhost ~]# 

""符号在元字符集合"["符号内外的作用是不一样的,在""符号内表示反向选择,在T]符号外则代表定位行首。反之,若想查找以某一特定字符结尾的行则可以使用"$"定位符。例如,执行以下命令即可实现查询以小数点(.)结尾的行。因为小数点(.)在正则表达式中也是一个元字符(后面会讲到),所以在这里需要用转义字符V"将具有特殊意义的字符转化成普通字符。

[root@localhost ~]# grep -n '\.$' test.txt 
1:he was short and fat.
2:he was weating a blue polo shirt with black pants.
3:The home of Football on BBC Sport online.
5:google is the best tools for search keyword.
14:Misfortunes never come alone/single.
15:I shouldn't have lett so tast.
[root@localhost ~]# 

当查询空白行时,执行"grep -n'^$'test.txt"命令即可。

[root@localhost ~]# grep -n '^$' test.txt 
9:
16:
[root@localhost ~]# 
4. 查找任意一个字符"."与重复字符"*"

前面提到,在正则表达式中小数点(.)也是一个元字符,代表任意一个字符。

例如执行以下命令就可以查找"w??d"的字符串,即共有四个字符,以w开头d结尾。

[root@localhost ~]# grep -n 'w..d' test.txt 
5:google is the best tools for search keyword.
7:a wood cross!
8:Actions speak louder than words
[root@localhost ~]# 

在上述结果中,"wood"字符串"w..d"匹配规则。若想要查询oo、ooo、ooooo等资料,则需要使用星号(*)元字符。但需要注意的是,"*"代表的是重复零个或多个前面的单字符。"o*"表示拥有零个(即为空字符)或大于等于一个"o"的字符,因为允许空字符,所以执行"grep-n 'o* test.txt"命令会将文本中所有的内容都输出打印。如果是"oo*",则第一个o必须存在,第二个o则是零个或多个o,所以凡是包含o、oo、ooo、ooo,等的资料都符合标准。同理,若查询包含至少两个o以上的字符串,则执行"grep -n 'ooo" test.txt"命令即可。

[root@localhost ~]# grep -n 'ooo*' test.txt 
3:The home of Football on BBC Sport online.
5:google is the best tools for search keyword.
7:a wood cross!
10:#woood #
11:#woooooooood #
13:I bet this place is really spooky late at night!
[root@localhost ~]# 

查询以w开头d结尾,中间包含至少一个o的字符串,执行以下命令即可实现。

[root@localhost ~]# grep -n 'woo*' test.txt 
5:google is the best tools for search keyword.
7:a wood cross!
8:Actions speak louder than words
10:#woood #
11:#woooooooood #
[root@localhost ~]# 

执行以下命令即可查询以w开头d结尾,中间的字符可有可无的字符串。

[root@localhost ~]# grep -n 'w.*d' test.txt 
1:he was short and fat.
5:google is the best tools for search keyword.
7:a wood cross!
8:Actions speak louder than words
10:#woood #
11:#woooooooood #
[root@localhost ~]# 

执行以下命令即可查询任意数字所在行。

[root@localhost ~]# grep -n '[0-9*]' test.txt 
4:the tongue is boneless but it breaks bones.12!
6:PI=3.14
[root@localhost ~]# grep -n '[0-9][0-9]*' test.txt 
4:the tongue is boneless but it breaks bones.12!
6:PI=3.14
[root@localhost ~]# 
5. 查找连续字符范围"{}"

在上面的示例中,使用了"."与"*"来设定零个到无限多个重复的字符,如果想要限制一个范围内的重复的字符串该如何实现呢?例如,查找三到五个o的连续字符,这个时候就需要使用基础正则表达式中的限定范围的字符""。因为""在 Shell中具有特殊意义,所以在使用"柠"字符时,需要利用转义字符V",将""字符转换成普通字符。""字符的使用方法如下所示。

查询两个o的字符

[root@localhost ~]# grep -n 'o\{2\}' test.txt 
3:The home of Football on BBC Sport online.
5:google is the best tools for search keyword.
7:a wood cross!
10:#woood #
11:#woooooooood #
13:I bet this place is really spooky late at night!
[root@localhost ~]# 

查询以w开头以d结尾,中间包含2~5个o的字符串

[root@localhost ~]# grep -n 'wo\{2,5\}d' test.txt 
7:a wood cross!
10:#woood #
[root@localhost ~]# 

查询以w开头以d结尾,中间包含2个或2个以上o的字符串

[root@localhost ~]# grep -n 'wo\{2,\}d' test.txt 
7:a wood cross!
10:#woood #
11:#woooooooood #
[root@localhost ~]# 

2. 元字符总结

通过上面几个简单的示例,可以了解到常见的基础正则表达式的元字符主要包括以下几个

4.1.3 扩展正则表达式

通常情况下会使用基础正则表达式就已经足够了,但有时为了简化整个指令,需要使用范围更广的扩展正则表达式。例如,使用基础正则表达式查询除文件中空白行与行首为"#"之外的行(通常用于查看生效的配置文件),执行"grep -v*'test.txt \| grep -v\^#""即可实现。这里需要使用管道命令来搜索两次。如果使用扩展正则表达式,可以简化为"egrep-V\^/^#'test.txt",其中,单引号内的管道符号表示或者(or)

此外,grep命令仅支持基础正则表达式,如果使用扩展正则表达式,需要使用egrep或awk命令。awk命令在后面的小节进行讲解,这里我们直接使用egrep命令。egrep命令与 grep命令的用法基本相似。egrep命令是一个搜索文件获得模式,使用该命令可以搜索文件中的任意字符串和符号,也可以搜索一个或多个文件的字符串,一个提示符可以是单个字符、一个字符串、一个字或一个句子。

与基础正则表达式类型相同,扩展正则表达式也包含多个元字符,常见的扩展正则表达式的元字符主要包括以下几个,如表4-2所示。

4.2 文本处理器

在Linux/UNIX系统中包含很多种类的文本处理器或文本编辑器,其中包括我们之前学习过的VIM编辑器与grep等。而grep, sed,awk更是Shell编程中经常用到的文本处理工具,被称之为 Shell 编程三剑客。

4.2.1 sed工具

sed ( Stream EDitor)是一个强大而简单的文本解析转换工具,可以读取文本,并根据指定的条件对文本内容进行编辑(删除、替换、添加、移动等),最后输出所有行或者仅输出处理的某些行。sed也可以在无交互的情况下实现相当复杂的文本处理操作,被广泛应用于Shell脚本中,用以完成各种自动化处理任务。

sed 的工作流程主要包括读取、执行和显示三个过程。

  1. 读取: sed 从输入流(文件、管道、标准输入)中读取一行内容并存储到临时的缓冲区中(又称模式空间,pattern space)。
  2. 执行:默认情况下,所有的sed命令都在模式空间中顺序地执行,除非指定了行的地址,否则sed命令将会在所有的行上依次执行。
  3. 显示:发送修改后的内容到输出流。在发送数据后,模式空间将会被清空。

在所有的文件内容都被处理完成之前,上述过程将重复执行,直至所有内容被处理完。

注意:默认情况下所有的sed命令都是在模式空间内执行的,因此输入的文件并不会发生任何变化,除非是用重定向存储输出。

1. sed命令常见用法

通常情况下调用sed命令有两种格式,如下所示。其中,"参数"是指操作的目标文件,当存在多个操作对象时用,文件之间用逗号","分隔;而scriptfile表示脚本文件,需要用"-f选项指定,当脚本文件出现在目标文件之前时,表示通过指定的脚本文件来处理输入的目标文件。

sed [选项] '操作' 参数
sed [选项] -f scriptfile 参数

常见的sed命令选项主要包含以下几种。

  1. -e或--expression=:表示用指定命令或者脚本来处理输入的文本文件。
  2. -f或--file=:表示用指定的脚本文件来处理输入的文本文件。
  3. -h或--help:显示帮助。
  4. -n、 --quiet或silent:表示仅显示处理后的结果。
  5. -i:直接编辑文本文件。

"操作"用于指定对文件操作的动作行为,也就是sed 的命令。通常情况下是采用的"[n1[.n2]"操作参数的格式。 n1、n2是可选的,代表选择进行操作的行数,如操作需要在5~20行之间进行,则表示为""5,20动作行为"。常见的操作包括以下几种。

  1. a:增加,在当前行下面增加一行指定内容。
  2. c:替换,将选定行替换为指定内容。
  3. d:删除,删除选定的行。
  4. i:插入,在选定行上面插入一行指定内容。
  5. p:打印,如果同时指定行,表示打印指定行;如果不指定行,则表示打印所有内容:如果有非打印字符,则以ASCIl码输出。其通常与"-n"选项一起使用。
  6. s:替换,替换指定字符。
  7. y:字符转换。

2. 用法示例

1. 输出符合条件的文本(p表示正常输出)
[root@localhost ~]# sed -n 'p' test.txt         //输出所有内容,等同于cat test.txt
he was short and fat.
he was weating a blue polo shirt with black pants.
The home of Football on BBC Sport online.
the tongue is boneless but it breaks bones.12!
google is the best tools for search keyword.
PI=3.14
a wood cross!
Actions speak louder than words

#woood #
#woooooooood #
AxyzxyzxyzxyzC
I bet this place is really spooky late at night!
Misfortunes never come alone/single.
I shouldn't have lett so tast.

[root@localhost ~]# sed -n '3p' test.txt         //输出第3行
The home of Football on BBC Sport online.
[root@localhost ~]# sed -n '3,5p' test.txt         //输出3~5行
The home of Football on BBC Sport online.
the tongue is boneless but it breaks bones.12!
google is the best tools for search keyword.
[root@localhost ~]# sed -n 'p;n' test.txt         //输出所有奇数行,n表示读入下一行资料
he was short and fat.
The home of Football on BBC Sport online.
google is the best tools for search keyword.
a wood cross!

#woooooooood #
I bet this place is really spooky late at night!
I shouldn't have lett so tast.
[root@localhost ~]# sed -n 'n;p' test.txt         //输出所有偶数行,n表示读入下一行资料
he was weating a blue polo shirt with black pants.
the tongue is boneless but it breaks bones.12!
PI=3.14
Actions speak louder than words
#woood #
AxyzxyzxyzxyzC
Misfortunes never come alone/single.

[root@localhost ~]# sed -n '1,5{p;n}' test.txt         //输出第1~5行之间的奇数行(第1/3/5行)
he was short and fat.
The home of Football on BBC Sport online.
google is the best tools for search keyword.
[root@localhost ~]# sed -n '10,${n;p}' test.txt         //输出第10行至文件尾之间的偶数行
#woooooooood #
I bet this place is really spooky late at night!
I shouldn't have lett so tast.
[root@localhost ~]# 

在执行"sed -n'10,${n;py'test.txt"命令时,读取的第1行是文件的第10行,读取的第2行是文件的第11行,依此类推,所以输出的偶数行是文件的第11行、13行直至文件结尾,其中包括空行。

以上是sed命令的基本用法,sed命令结合正则表达式时,格式略有不同,正则表达式以"""包围。例如,以下操作是sed命令与正则表达式结合使用的示例。

[root@localhost ~]# sed -n '/the/p' test.txt         //输出包含the的行
the tongue is boneless but it breaks bones.12!
google is the best tools for search keyword.
[root@localhost ~]# sed -n '4,/the/p' test.txt         //输出从第4行至第一个包含the的行
the tongue is boneless but it breaks bones.12!
google is the best tools for search keyword.
[root@localhost ~]# sed -n '/the/=' test.txt         //输出包含the的行所在的行号,等号(=)用来输出行号
4
5
[root@localhost ~]# sed -n '/^PI/p' test.txt         //输出以PI开头的行
PI=3.14
[root@localhost ~]# sed -n '/[0-9]$/p' test.txt         //输出以数字结尾的行
PI=3.14
[root@localhost ~]# sed -n '/\<wood\>/p' test.txt         //输出包含单词wood的行,\<、\>代表单词边界
a wood cross!
[root@localhost ~]# 
2. 删除符合条件的文本(d)

因为后面的示例还需要使用测试文件 test.txt,所以在执行删除操作之前需要先将测试文件备份。以下示例分别演示了sed命令的几种常用删除用法。

下面命令中nl命令用于计算文件的行数,结合该命令可以更加直观地查看到命令执行的结果。

[root@localhost ~]# nl test.txt | sed '3d'        //删除第3行
     1	he was short and fat.
     2	he was weating a blue polo shirt with black pants.
     4	the tongue is boneless but it breaks bones.12!
     5	google is the best tools for search keyword.
     6	PI=3.14
     7	a wood cross!
     8	Actions speak louder than words
       
     9	#woood #
    10	#woooooooood #
    11	AxyzxyzxyzxyzC
    12	I bet this place is really spooky late at night!
    13	Misfortunes never come alone/single.
    14	I shouldn't have lett so tast.
       
[root@localhost ~]# nl test.txt | sed '3,5d'            //删除第3~5行
     1	he was short and fat.
     2	he was weating a blue polo shirt with black pants.
     6	PI=3.14
     7	a wood cross!
     8	Actions speak louder than words
       
     9	#woood #
    10	#woooooooood #
    11	AxyzxyzxyzxyzC
    12	I bet this place is really spooky late at night!
    13	Misfortunes never come alone/single.
    14	I shouldn't have lett so tast.
       
[root@localhost ~]# nl test.txt | sed '/cross/d'       
//删除包含cross的行,原本的第8行被删除;如果要删除不包含cross的行,用!符号表示取反操作
     1	he was short and fat.
     2	he was weating a blue polo shirt with black pants.
     3	The home of Football on BBC Sport online.
     4	the tongue is boneless but it breaks bones.12!
     5	google is the best tools for search keyword.
     6	PI=3.14
     8	Actions speak louder than words
       
     9	#woood #
    10	#woooooooood #
    11	AxyzxyzxyzxyzC
    12	I bet this place is really spooky late at night!
    13	Misfortunes never come alone/single.
    14	I shouldn't have lett so tast.
       
[root@localhost ~]# sed '/^[a-z]/d' test.txt         //删除以小写字母开头的行
The home of Football on BBC Sport online.
PI=3.14
Actions speak louder than words

#woood #
#woooooooood #
AxyzxyzxyzxyzC
I bet this place is really spooky late at night!
Misfortunes never come alone/single.
I shouldn't have lett so tast.

[root@localhost ~]# sed '/\.$/d' test.txt         //删除以"."结尾的行
the tongue is boneless but it breaks bones.12!
PI=3.14
a wood cross!
Actions speak louder than words

#woood #
#woooooooood #
AxyzxyzxyzxyzC
I bet this place is really spooky late at night!
    
[root@localhost ~]# sed '/^$/d' test.txt             //删除所有空行
he was short and fat.
he was weating a blue polo shirt with black pants.
The home of Football on BBC Sport online.
the tongue is boneless but it breaks bones.12!
google is the best tools for search keyword.
PI=3.14
a wood cross!
Actions speak louder than words
#woood #
#woooooooood #
AxyzxyzxyzxyzC
I bet this place is really spooky late at night!
Misfortunes never come alone/single.
I shouldn't have lett so tast.

注意:若是删除重复的空行,即连续的空行只保留一个,执行"sed -e '/^/{n;/\^/d}' test.txt "命令即可实现。其效果与"cat -s test.txt"相同,n表示读下一行数据

3. 替换符合条件的文本

在使用sed命令进行替换操作时需要用到s(字符串替换)、c(整行/整块替换)、y(字符转换)命令选项,常见的用法如下所示。

sed 's/the/THE/' test.txt         //将每行中的第一个the替换为THE
sed 's/I/L/2' test.txt            //将每行中的第2个I替换为L
sed 's/the/THE/g' test txt        //将文件中的所有the替换为THE
sed 's/o//g' test.txt             //将文件中的所有o删除(替换为空串)
sed 's/^/#/' test .txt            //在每行行首插入#号
sed '/the/s/^/#' test.txt         //在包含the的每行行首插入#号
sed 's/$/EOF/' test.txt           //在每行行尾插入字符串EOF
sed '3,5s/the/THE/g' test.txt     //将第3~5行中的所有the替换为THE
sed '/the/s/o/O/g' test.txt       //将包含the的所有行中的o替换为O
4. 迁移符合条件的文本

在使用sed命令迁移符合条件的文本时,常用到以下参数.

  1. H:复制到剪贴板;
  2. g、G:将剪贴板中的数据覆盖/追加至指定行;
  3. w:保存为文件;
  4. r:读取指定文件;
  5. a:追加指定内容。

具体操作方法如下所示。

sed '/the/{H;d};$G' test.txt            //将包含the的行迁移至文件末尾,{;}用于多个操作
sed '1,5{H;d}' test.txt                 //将第1~5行内容转移至第17行后
sed '/the/w out.file' test.txt          //将包含the的行另存为文件out.file
sed '/the/r /etc/hostname' test.txt     //将文件/etc/hostname的内容添加到包含the的每行以后
sed '3aNew' test.txt                    //在第3行后插入一个新行,内容为New
sed '/the/aNew' test.txt                //在包含the的每行后插入一个新行,内容为New
sed '3aNew1\nNew2' test.txt             //在第3行后插入多行内容,中间的\n表示换行
5. 使用脚本编辑文件

使用sed脚本将多个编辑指令存放到文件中(每行一条编辑指令),通过"-f"选项来调用。例如执行以下命令即可将第1~5行内容转移至第17行后。

sed '1,5{H;d};17G' test.txt            //将第1~5行内容转移至第17行后

以上操作可以改用脚本文件方式:

[root@localhost ~]# vi opt.list

1,5H
1,5d
17G

[root@localhost ~]# sed -f opt.list test.txt 
PI=3.14
a wood cross!
Actions speak louder than words

#woood #
#woooooooood #
AxyzxyzxyzxyzC
I bet this place is really spooky late at night!
Misfortunes never come alone/single.
I shouldn't have lett so tast.

[root@localhost ~]# 
6. sed直接操作文件示例

编写一个脚本,用来调整vsftpd服务配置,要求禁止匿名用户,但允许本地用户((也允许写入)。

4.2.2 awk工具

在 Linux/UNIX系统中,awk 是一个功能强大的编辑工具,逐行读取输入文本,并根据指定的匹配模式进行查找,对符合条件的内容进行格式化输出或者过滤处理,可以在无交互.的情况下实现相当复杂的文本操作,被广泛应用于 Shell脚本,完成各种自动化配置任务。

1. awk常见用法

通常情况下 awk所使用的命令格式如下所示,其中,单引号加上大括号""用于设置对数据进行的处理动作。awk可以直接处理目标文件,也可以通过"-f"读取脚本对目标文件进行处理。

awk 选项 '模式或条件 {编辑指令}' 文件1 文件2...            //过滤并输出文件中符合条件的内容
awk -f 脚本文件 文件1 文件2...                            //从脚本中调用编辑指令,过滤并输出内容

前面提到sed命令常用于一整行的处理,而 awk比较倾向于将一行分成多个"字段"然后再进行处理,且默认情况下字段的分隔符为空格或tab键。awk执行结果可以通过 print 的功能将字段数据打印显示。在使用awk命令的过程中,可以使用逻辑操作符&&"表示"与"、"1I"表示"或"、"! "表示"非";还可以进行简单的数学运算,如+、-、*、l、%、^分别表示加、减、乘、除、取余和乘方。

在Linux系统中letc/passwd是一个非常典型的格式化文件,各字段间使用":"作为分隔符隔开,Linux系统中的大部分日志文件也是格式化文件,从这些文件中提取相关信息是运维的日常工作内容之一。若需要查找出/etc/passwd 的用户名、用户ID、组ID等列,执行以下 awk命令即可。

[root@localhost ~]# awk -F':' '{print $1,$3,$4}' /etc/passwd
root 0 0
bin 1 1
daemon 2 2
adm 3 4
lp 4 7
sync 5 0
shutdown 6 0
halt 7 0
mail 8 12
operator 11 0
games 12 100
ftp 14 50
nobody 99 99
systemd-network 192 192
dbus 81 81
polkitd 999 998
sshd 74 74
postfix 89 89
chrony 998 996
[root@localhost ~]# 

awk 从输入文件或者标准输入中读入信息,与sed一样,信息的读入也是逐行读取的。不同的是 awk将文本文件中的一行视为一个记录,而将一行中的某一部分(列)作为记录中的一个字段(域)。为了操作这些不同的字段,awk借用shell中类似于位置变量的方法,用$1、$2、3...顺序地表示行(记录)中的不同字段。另外awk用O表示整个行(记录)。不同的字段之间是通过指定的字符分隔。awk默认的分隔符是空格。awk允许在命令行中用"-F分隔符"的形式来指定分隔符。在上述示例中,awk命令对letc/passwd文件的处理过程如图4.1所示。

awk 包含几个特殊的内建变量(可直接用)如下所示:

  1. FS:指定每行文本的字段分隔符,默认为空格或制表位。
  2. NF:当前处理的行的字段个数。
  3. NR:当前处理的行的行号(序数)。
  4. $0:当前处理的行的整行内容。
  5. $n:当前处理行的第n个字段(第n列)。
  6. FILENAME:被处理的文件名。
  7. RS:数据记录分隔,默认为\n,即每行为一条记录。

2. 用法示例

1. 按行输出文本
2. 按字段输出文本
3. 通过管道、双引号调用Shell命令

4.2.3 sort 工具

在Linux系统中,常用的文件排序工具有三种: sort、uniq、wc。本章将介绍前两种工具的用法。

sort是一个以行为单位对文件内容进行排序的工具,也可以根据不同的数据类型来排序。例如数据和字符的排序就不一样。sort命令的语法为"sort [选项]参数",其中常用的选项包括以下几种。

  1. -f:忽略大小写;
  2. -b:忽略每行前面的空格
  3. -M:按照月份进行趴下
  4. -n:按照数字进行排序
  5. -r:反向排序
  6. -u:等同于uniq,表示相同的数据仅显示一行
  7. -t:指定分隔符,默认使用[Tab]捡分割
  8. -o<输出文件>:将排序后的结构转存至指定文件
  9. -k:指定排序区域
    示例1:将/etc/passwd文件中的账号进行排序。

示例2:将/etc/passwd文件中第三列进行反向排序。

[root@localhost ~]# sort -t ':' -rk 3 /etc/passwd
nobody:x:99:99:Nobody:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
chrony:x:998:996::/var/lib/chrony:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
halt:x:7:0:halt:/sbin:/sbin/halt
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
sync:x:5:0:sync:/sbin:/bin/sync
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
bin:x:1:1:bin:/bin:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
[root@localhost ~]# 

示例3:将/etc/passwd文件中第三列进行排序,并将输出内容保存至user.txt文件中。

[root@localhost ~]# sort -t ':' -rk 3 /etc/passwd -o user.txt
[root@localhost ~]# cat user.txt 
nobody:x:99:99:Nobody:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
chrony:x:998:996::/var/lib/chrony:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
halt:x:7:0:halt:/sbin:/sbin/halt
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
sync:x:5:0:sync:/sbin:/bin/sync
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
bin:x:1:1:bin:/bin:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
[root@localhost ~]# 

4.2.4 uniq 工具

Uniq工具在Linux系统中通常与sort命令结合使用,用于报告或者忽略文件中的重复行。具体的命令语法格式为: uniq[选项]参数。其中常用选项包括以下几种。

  1. -c:进行计数
  2. -d:仅显示重复行
  3. -u:仅显示出现一次的行
    示例1:删除 testfile 文件中的重复行。

示例2:删除testfile文件中的重复行,并在行首显示该行重复出现的次数。

示例3:查找testfile 文件中的重复行。

4.2.5 tr 工具

tr命令常用来对来自标准输入的字符进行替换、压缩和删除。可以将一组字符替换之后变成另一组字符,经常用来编写优美的单行命令,作用很强大。

tr [选项][参数]

其常用选项包括以下内容。

  1. -c:取代所有不属于第一字符集的字符;
  2. -d:删除所有属于第一字符集的字符;
  3. -s:把连续重复的字符以单独一个字符表示;
  4. -t:先删除第一字符集较第二字符集多出的字符。
    示例1:将输入字符由大写转换为小写。

示例2:压缩输入中重复的字符。

示例3:删除字符串中某些字符。

相关推荐
终将老去的穷苦程序员20 分钟前
将 WSL(Windows Subsystem for Linux)移动到另一个盘上
linux·运维·windows
go&Python1 小时前
centos 7.9 离线环境安装GPU服务环境
linux·运维·centos
Niiiii..1 小时前
Linux 下常用命令
linux·运维·服务器
来自于狂人2 小时前
ansible常用命令
linux·运维·ansible
念晚9172 小时前
Linux各种命令——tac命令,more 命令, less命令,head命令,tail命令,file 命令, stat 命令
linux·运维·服务器·前端·网络·数据库·less
铁蛋Q2 小时前
Linux基础指令
linux·运维·服务器
今君3 小时前
【linux】网络基础(1)
linux·运维·网络
软件技术NINI3 小时前
压缩包怎么解压,解压压缩包不损坏文件
linux·运维·服务器
原机小子4 小时前
Perl正则表达式捕获组:深入探索与实战应用
开发语言·正则表达式·perl
Fountyuan4 小时前
C#正则表达式的基本语法
开发语言·正则表达式·c#