理论+实操:shell 变成之正则表达式与文件处理器

文章目录


shell 变成之正则表达式与文件处理器

前言:

  • 基础正则表达式
  • 扩展正则表达式
  • sed工具使用方法
  • awk工具使用方法

一 : 正则表达式

之前学习了 Shell 脚本的基础用法,已经可以利用条件判断、循环等语句编辑 Shell 脚本。接下来我们将开始介绍一个很重要的概念——正则表达式(RegularExpression,RE)。

正则表达式是一个工具

1.1 正则表达式概述

下面先来了解一下正则表达式的定义及用途。

1.2正则表达式的定义

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

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

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

1.3 正则表达式用途

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

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

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

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

二 : 基础正则表达式(grep)

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

2.1基础正则表达式示例

以httpd.conf为例

[root@localhost opt]# cp /etc/httpd/conf/httpd.conf /opt
cp: overwrite ‘/opt/httpd.conf’? y
[root@localhost opt]# ls
httpd.conf  jbxx  rh
[root@localhost opt]# 

2.1.1 查找特定字符

​ 查找特定字符非常简单,如执行以下命令即可从httpd.conf 文件中查找出特定字符“the” 所在位置。其中

  • “-n”表示显示行号
  • “-i”表示不区分大小写
  • 使用单引号去确定要检索的内容

​ 命令执行后,符合匹配标准的字符,字体颜色会变为红色。

[root@localhost opt]# grep -n 'the' httpd.conf 
2:# This is the main Apache HTTP server configuration file.  It contains the
3:# configuration directives that give the server its instructions.
9:# Do NOT simply read the instructions in here

​ 若反向选择,如查找不包含“the”字符的行,则需要通过 grep 命令的“-vn”选项实现。

  • -v 表示反向选择
[root@localhost opt]# grep -vn 'the' httpd.conf 
1:#
4:# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
5:# In particular, see 
6:# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>

2.1.2 利用 [ ] 来查找集合字符

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

[root@localhost opt]# grep -n 'sh[io]rt' httpd.conf 
[root@localhost opt]# echo $?
1
[root@localhost opt]# echo 'shirt' >> httpd.conf 
[root@localhost opt]# echo 'short' >> httpd.conf 
[root@localhost opt]# 

文件内没有,加两个进去

[root@localhost opt]# grep -n 'sh[io]rt' httpd.conf 
354:shirt
355:short

这种是以或者的模式去匹配,只能从中括号中去轮流匹配一个字符

在grep中,只要检索的是字符,就加单引号

2.1.3 查找连续字符

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

wd
wod
wood
woood
wooooooood
"先在测试文件中加一些测试字符串"
[root@localhost opt]# grep -n 'oo' httpd.conf 
16:# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
358:wood
359:woood
360:wooooooood

这里只截取部分,可以跟做

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

[root@localhost opt]# grep -n '[^w]oo' httpd.conf 
332:#ErrorDocument 500 "The server made a boo boo."
359:woood
360:wooooooood

  • ^放在括号里面就是取反,不包含的意思

  • ^放在括号外面就是以什么为开头

在上述命令的执行结果中发现“woood”与“wooooooood”也符合匹配规则

二者虽然也均包含“w”,但其实通过执行加红结果就可以看出“#woood #”中红色显示的是“ooo”,而“oo”前面的“o”是符合匹配规则的。同理 “#woooooood #”也符合匹配规则。

2.1.4 连续字符前面不为字母

若不希望“oo”前面存在小写字母,可以使用“grep –n‘[^a-z]oo’test.txt”命令实现,其中

  • “a-z”表示小写字母,
  • 大写字母则通过“A-Z”表示
  • 连续数字用[0-9]表示
[root@localhost opt]# grep -n '[^a-zA-Z]oo' httpd.conf 
[root@localhost opt]# echo "123oo" >> httpd.conf 
[root@localhost opt]# echo "3oo" >> httpd.conf 
[root@localhost opt]# grep -n '[^a-zA-Z]oo' httpd.conf 
362:123oo
363:3oo

查找包含数字的行可以通过“grep –n‘[0-9]’test.txt”命令来实现。

[root@localhost opt]# grep -n '[^0-9]oo' httpd.conf 
358:wood
359:woood
360:wooooooood

2.1.5 查找行首^与行尾字符$

基础正则表达式包含两个定位元字符:

  • “^”(行首)与“$”(行尾)。

在上面的示例中,查询“the”字符串时出现了很多包含“the”的行,如果想要查询以“the”字符串为行首的行,则可以通过“^”元字符来实现。

[root@localhost opt]# grep -n '^the' httpd.conf 
[root@localhost opt]# echo $?
1
[root@localhost opt]# echo the this is test >> httpd.conf 
[root@localhost opt]# grep -n '^the' httpd.conf 
364:the this is test

查询以小写字母开头的行可以通过“[a-z]”规则来过滤,查询大写字母开头的行则使用“[A-Z]”规则,若查询不以字母开头的行则使用1来选择

[root@localhost opt]# grep -n '^[^a-zA-Z]' httpd.conf 
1:#
2:# This is the main Apache HTTP server configuration file.  It contains the
3:# configuration directives that give the server its instructions.
4:# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
5:# In particular, see 
6:# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
7:# for a discussion of each configuration directive.

2.1.6 ^$符号详细解释以及转义符\

“^”符号在元字符集合“[]”符号内外的作用是不一样的,在“[]”符号内表示反向选择,在“[]”符号外则代表定位行首。反之,若想查找以某一特定字符结尾的行则可以使用“$”定位符。

例如,执行以下命令即可实现查询以小数点(.)结尾的行。因为小数点(.) 在正则表达式中也是一个元字符(后面会讲到),所以在这里需要用**转义字符“\”**将具有特 殊意义的字符转化成普通字符。

  • 查询小数点.需要使用转译符号\,否则会将其视为特殊含义的元字符----代表一个任意字符
[root@localhost opt]# grep -n '\.$' httpd.conf 
3:# configuration directives that give the server its instructions.
4:# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
7:# for a discussion of each configuration directive.
19:# interpreted as '/log/access_log'.

2.1.7 当查询空白行“^KaTeX parse error: Expected group after '^' at position 15: ”时,执行“grep –n‘^̲’test.txt”命令即可

2.1.8 查找任意一个字符“.”与重复字符“*”

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

例如, 执行以下命令就可以查找“w…d”的字符串,即共有四个字符,以 w 开头 d 结尾。中间的两个字符可以是任意字符,甚至是空格

[root@localhost opt]# grep -n 'w..d' httpd.conf 
108:# Note that from this point forward you must specifically allow
148:    # It can be "All", "None", or any combination of the keywords:
358:wood
[root@localhost opt]# echo w  d >> httpd.conf 
[root@localhost opt]# grep -n 'w..d' httpd.conf 
108:# Note that from this point forward you must specifically allow
148:    # It can be "All", "None", or any combination of the keywords:
358:wood
365:w  d

在上述结果中,“wood”字符串“w…d”匹配规则。

若想要查询 oo、ooo、ooooo 等资料,则需要使用星号 * 元字符。

但需要注意的是, * 代表的是重复前面的一个字符零个或多个——即大于等于0。“o * ”表示拥有零个(即为空字符)或大于等于一个“o”的字符,因为允许空字符,所以执行“grep –n’o * ’ 命令会将文本中所有的内容都输出打印。

如果是“oo*” 则第一个 o 必须存在,第二个 o 则是零个或多个 o,所以凡是包含 o、oo、ooo、ooo,等的资料都符合标准。

同理,若查询包含至少两个 o 以上的字符串,则执行“grep –n‘ooo* 文件路径’ ”命令即可。

[root@localhost opt]# grep -n 'ooo*' httpd.conf 
16:# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
17:# with ServerRoot set to '/www' will be interpreted by the
358:wood
359:woood
360:wooooooood
362:123oo
363:3oo

  • 查询以 w 开头 d 结尾,中间包含至少一个 o 的字符串,执行以下命令即可实现。
[root@localhost opt]# grep -n 'woo*d' httpd.conf 
357:wod
358:wood
359:woood
360:wooooooood

2.1.9 查询以 w 开头 d 结尾,中间的字符可有可无的字符串。

[root@localhost opt]# grep -n 'w.*d' httpd.conf 
9:# Do NOT simply read the instructions in here without understanding
10:# what they do.  They're here only as hints or reminders.  If you are unsure
11:# consult the online docs. You have been warned.  

可以发现, . 代表任意字符,* 代表重复任意个,即可以是一连串的字符串

2.1.10 查询任意数字所在行

[root@localhost opt]# grep -n '[0-9][0-9]*' httpd.conf 
4:# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
6:# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>

其中至少要有一个数,所以需要先写一个[0-9],然后后面的[0-9]作为一个匹配的参数存在

  • *只匹配前面的一个字符,0次或多次

2.1.11 查找连续字符范围“{}”

在上面的示例中,我们使用“.”与“*”来设定零个到无限多个重复的字符

如果想要限制一个范围内的重复的字符串该如何实现?

例如,查找三到五个 o 的连续字符,这个时候就需要使用基础正则表达式中的限定范围的字符“{}”。

因为“{}”在 Shell 中具有特殊 意义,所以在使用“{}”字符时,需要利用转义字符“\”,将“{}”字符转换成普通字符。 “{}”字符的使用方法如下所示。

2.1.12 查询两个o的字符

[root@localhost opt]# grep -n 'o\{2\}' httpd.conf 
16:# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
17:# with ServerRoot set to '/www' will be interpreted by the

’ o \ { 2 \ } ’

备注:没有空格,此处添加空格是为了把他们分开

单引号内

  • o代表要查询的字符
  • \代表转义,将{}变成普通字符
  • 大括号里面的2代表个数,即两个o;若是5就是五个o

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

[root@localhost opt]# grep -n 'wo\{2,5\}d' httpd.conf 
358:wood
359:woood

在查询两个的基础上,若是指定一个范围,则大括号内使用逗号隔开区间

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

[root@localhost opt]# grep -n 'wo\{2,\}d' httpd.conf 
358:wood
359:woood
360:wooooooood

若是范围是>=2,没有上限值,则默认不写

2.2 常见元字符总结

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

  • 基础正则表达式常见元字符
元字符 作用
^ 匹配输入字符串的开始位置。除非在方括号表达式中使用,表示不包含该字符集合。要匹配“^”字符本身,请使用“^”
$ 匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则“KaTeX parse error: Undefined control sequence: \n at position 6: ”也匹配‘\̲n̲’或‘\r’。要匹配“”字符本身,请使用“$”
. 匹配除“\r\n”之外的任何单个字符
\ 将下一个字符标记为特殊字符、原义字符、向后引用、八进制转义符。例如,‘n’匹配字符“n”。 ‘\n’匹配换行符。序列‘\ \’匹配“\”,而‘\ (’则匹配“(”
* 匹配前面的子表达式零次或多次。要匹配“*”字符,请使用“*”
[ ] 字符集合。匹配所包含的任意一个字符。例如,“[abc]”可以匹配“plain”中的“a”
[^] 赋值字符集合。匹配未包含的一个任意字符。例如,“[^abc]”可以匹配“plain”中“plin”中的任何一个字母
[n-(n+1) ] 字符范围。匹配指定范围内的任意一个字符。例如,“[a-z]”可以匹配“a”到“z”范围内的任意一个小写字母字符。注意:只有连字符(-)在字符组内部,并且出现在两个字符之间时,才能表示字符的范围;如果出现在字符组的开头,则只能表示连字符本身
{n} n 是一个非负整数,匹配确定的 n 次。例如,“o{2}”不能匹配“Bob”中的“o”,但是能匹配“food”中的两个 o
{n,} n 是一个非负整数,至少匹配 n 次。例如,“o{2,}”不能匹配“Bob”中的“o”,但能匹配“foooood”中的所有 o。“o{1,}”等价于“o+”。“o{0,}”则等价于“o*”
{n,m} m 和n 均为非负整数,其中 n<=m,最少匹配 n 次且最多匹配 m 次
  • 备注:时刻注意括号需要使用转义符号

[ ]内的单个字符与单个字符之间是或的关系,与外面的字符按顺序组成多个单词,这种写法类似一个网段的汇总

三 :扩展正则表达式

通常情况下会使用基础正则表达式就已经足够了,但有时为了简化整个指令,需要使用范围更广的扩展正则表达式。

例如,使用基础正则表达式查询除文件中空白行与行首为“#” 之外的行(通常用于查看生效的配置文件),执行“grep –v‘^$’test.txt | grep –v ‘^#’”即可实现。这里需要使用管道命令来搜索两次。

如果使用扩展正则表达式,可以简化为“egrep –v‘$|#’test.txt”,其中,单引号内的管道符号表示或者(or)。

此外,grep 命令仅支持基础正则表达式,如果使用扩展正则表达式,需要使用 egrep 或 awk 命令。awk 命令在后面的小节进行讲解,这里我们直接使用 egrep 命令。

egrep 命令与 grep 命令的用法基本相似。egrep 命令是一个搜索文件获得模式,使用该命令可以搜索文件中的任意字符串和符号,也可以搜索一个或多个文件的字符串,一个提示符可以是单个字符、一个字符串、一个字或一个句子。

3.1 扩展正则表达式选项

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

  • 扩展正则表达式egrep 常见元字符
元字符 作用与示例
+ 作用:重复一个或者一个以上的前一个字符 示例:执行“egrep -n ‘wo+d’ test.txt”命令,即可查询"wood" “woood” "woooooood"等字符串
作用:零个或者一个的前一个字符 示例:执行“egrep -n ‘bes?t’ test.txt”命令,即可查询“bet”“best”这两个字符串
| 作用:使用或者(or)的方式找出多个字符 示例:执行“egrep -n 'of | is | on ’ test.txt ” 命令即可查询of 或者 if 或者on 字符串
() 作用:查找“组”字符串 示例:“egrep -n ‘t(a|e)st’ test.txt ”。 “tast”与“test”因为这两个单词的“t”与“st”是重复的,所以将“a”与“e”列于“()”符号当中,并以“|”或含义符号分隔,即可查询“tast”或者“test”字符串
()+ 作用:辨别多个重复的组 示例:“egrep -n ‘A(xyz)+C’ test.txt” 。该命令是查询开头是"A"结尾是“C”,中间有一个以上的“xyz”字符串的意思
  • ()+:+表示至少有一次,不能一次没有

  • 使用扩展,grep头需要加e

3.2 演示

  • +演示
[root@localhost opt]# egrep -n 'wo+d' httpd.conf 
357:wod
358:wood
359:woood
360:wooooooood
[root@localhost opt]# grep -n 'wo\{1,\}d' httpd.conf 
357:wod
358:wood
359:woood
360:wooooooood
[root@localhost opt]# egrep -n 'wo\{1,\}d' httpd.conf 
[root@localhost opt]# echo $?
1
[root@localhost opt]# grep -n 'woo*d' httpd.conf 
357:wod
358:wood
359:woood
360:wooooooood

  • ?演示

  • 对前一个字符的存在表示疑问,是存在还是不存在

  • 真与假区别,也就是查找wod或者wd的字符串

  • ?表示前面的一个字符要么出现,要么不出现

[root@localhost opt]# egrep -n 'wo?d' httpd.conf 
168:# The following lines prevent .htaccess and .htpasswd files from being 
356:wd
357:wod
[root@localhost opt]# grep -n 'wo\{0,1\}d' httpd.conf 
168:# The following lines prevent .htaccess and .htpasswd files from being 
356:wd
357:wod

  • | 演示
[root@localhost opt]# egrep -n 'wd|wood' httpd.conf 
168:# The following lines prevent .htaccess and .htpasswd files from being 
356:wd
358:wood
[root@localhost opt]# echo tast >> httpd.conf 
[root@localhost opt]# egrep -n 't(e|a)st' httpd.conf 
364:the this is test
366:tast
[root@localhost opt]# grep -n 'test' httpd.conf && grep -n 'tast' httpd.conf 
364:the this is test
366:tast
[root@localhost opt]# grep -n 'wd' httpd.conf && grep -n 'wood' httpd.conf 
168:# The following lines prevent .htaccess and .htpasswd files from being 
356:wd
358:wood

  • () 演示

  • (),效果与[ ]一样,但是需要用 | 隔开;

  • [ ]只能查找单个,()可以连续字符

[root@localhost opt]# egrep -n 't(e|a)st' httpd.conf 
364:the this is test
366:tast
[root@localhost opt]# grep -n 't[e|a]st' httpd.conf 
364:the this is test
366:tast
[root@localhost opt]# grep -n 't(e|a)st' httpd.conf 
[root@localhost opt]# echo $?
1
[root@localhost opt]# egrep -n 't[e|a]st' httpd.conf 
364:the this is test
366:tast

  • ()+ 演示
  • 后面的+代表()内容为一次或者多次
[root@localhost opt]# egrep -n 'q(xyz)+s' httpd.conf 
367:qxyzxyzxyzxyzs
368:qxyzxyzs
369:qxyzqxyzs
[root@localhost opt]# grep -n 'q(xyz)\{1,\}s' httpd.conf 
[root@localhost opt]# echo $?
1
[root@localhost opt]# grep -n 'qxyz\{1,\}s' httpd.conf 
369:qxyzqxyzs
[root@localhost opt]# grep -n 'q[xyz]\{1,\}s' httpd.conf 
367:qxyzxyzxyzxyzs
368:qxyzxyzs
369:qxyzqxyzs
370:qxyqzxyzs
[root@localhost opt]# grep -n 'q'xyz'\{1,\}s' httpd.conf 
369:qxyzqxyzs
[root@localhost opt]# grep -n 'q"xyz"\{1,\}s' httpd.conf 
[root@localhost opt]# echo $?
1
[root@localhost opt]# grep -n 'q\{xyz\}\{1,\}s' httpd.conf 
grep: Invalid content of \{\}

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

四: sed 工具

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

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

  • 读取:sed 从输入流(文件、管道、标准输入)中读取一行内容并存储到临时的缓冲区中(又称模式空间,pattern space)。

  • 执行:默认情况下,所有的 sed 命令都在模式空间中顺序地执行,除非指定了行的地址,否则 sed 命令将会在所有的行上依次执行。

  • 显示:发送修改后的内容到输出流。再发送数据后,模式空间将会被清空。

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

sed会把文件拷贝到缓存中,然后再缓存中修改,直接编译是 -i

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

4.1 sed命令常见用法

通常情况下调用 sed 命令有两种格式

其中,“参数”是指操作的目标文件,当存在多个操作对象时用,文件之间用逗号“,”分隔;

而 scriptfile 表示脚本文件,需要用“-f”选项指定,当脚本文件出现在目标文件之前时,表示通过指定的脚本文件来处理输入的目标文件。

  • sed[选项] ‘操作’ 参数

  • sed [选项] -f scriptfile 参数

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

  • -e 或–expression=:表示用指定命令或者脚本来处理输入的文本文件,可以指定多个操作;若是后面只有一个命令,也可以省略,但是最好还是写上,养成习惯

  • -f 或–file=:表示用指定的脚本文件来处理输入的文本文件。

  • -h 或–help:显示帮助。

  • -n、–quiet 或 silent:表示仅显示处理后的结果。

  • -i:直接编辑文本文件。

  • -r : 可以使用扩展

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

  • a:增加,在当前行下面增加一行指定内容。

  • c:替换,将选定行替换为指定内容。

  • d:删除,删除选定的行。

  • i:插入,在选定行上面插入一行指定内容。

  • p:打印,如果同时指定行,表示打印指定行;如果不指定行,则表示打印所有内容;如果有非打印字符,则以 ASCII 码输出。其通常与“-n”选项一起使用。

  • s:替换,替换指定字符

  • y:字符转换。

4.3 用法示例

4.3.1 输出符合条件的文本(p表示正常输出)

  • 输出p全文件 -n 查看结果 -e 后面接命令,单条命令可以省略不写
[root@localhost opt]# sed -ne 'p' httpd.conf
"相当于cat"
  • 输出指定的第三行
[root@localhost opt]# sed -ne '3p' httpd.conf 
# configuration directives that give the server its instructions.

  • 输出指定的第三行到第五行的内容
[root@localhost opt]# sed -ne '3,5p' httpd.conf 
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 

  • 输出当前文本的所有奇数行
[root@localhost opt]# sed -ne 'p;n' httpd.conf 
#
# configuration directives that give the server its instructions.
# In particular, see 
# for a discussion of each configuration directive.

可以理解为:先打印输出一行,然后下一行no,不打印;循环往复,即只打印奇数行

  • 输出所有偶数行
[root@localhost opt]# sed -ne 'n;p' httpd.conf 
# This is the main Apache HTTP server configuration file.  It contains the
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>

  • 输入第1行到第5行内容的奇数行
[root@localhost opt]# sed -ne '1,5{p;n}' httpd.conf 
#
# configuration directives that give the server its instructions.
# In particular, see 

  • 输入第五行到最后一行内容的奇数行
[root@localhost opt]# sed -ne '5,${p;n}' httpd.conf 
# In particular, see 
# for a discussion of each configuration directive.
# Do NOT simply read the instructions in here without understanding
# consult the online docs. You have been warned.  

[root@localhost opt]# nl httpd.conf | sed -ne '2,6{p;n}' 
     2  # This is the main Apache HTTP server configuration file.  It contains the
     4  # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
     6  # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
[root@localhost opt]# nl httpd.conf | sed -ne '2,6{n;p}' 
     3  # configuration directives that give the server its instructions.
     5  # In particular, see 
     7  # for a discussion of each configuration directive.

虽然到了6,没有了,但是后面的p会强制执行,把下一行给强制打出来

​ 在执行“sed –n ‘10,${n;p}’ test.txt”命令时,读取的第 1 行是文件的第 10 行,

读取的第 2 行是文件的第 11 行,依此类推,所以输出的偶数行是文件的第 11 行、13 行直至文件结尾,其中包括空行。

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

  • 输出包含the的行
[root@localhost opt]# sed -ne '/the/p' httpd.conf 
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure

  • 从第350行开始输出,持续到第一个有the的行结束
[root@localhost opt]# sed -ne '350,/the/p' httpd.conf 
# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.

  • 输出包含the的行的行号,可以用来查看关键字都在哪一行
[root@localhost opt]# sed -ne '/the/=' httpd.conf 
2
3
9
10
11

  • 输出以w为开头(^w)的行
[root@localhost opt]# sed -ne '/^w/p' httpd.conf 
wd
wod
wood
woood
wooooooood
w  d

  • 输出以数字为结尾的行
[root@localhost opt]# sed -ne '/[0-9]$/p' httpd.conf 
#Listen 12.34.56.78:80
Listen 80
#ServerName www.example.com:80
AddDefaultCharset UTF-8

  • 输出详细单词的行,指定的单词需要用<>指定,<>需要用转义符号加以解释,即\ < \ >
[root@localhost opt]# echo the >> httpd.conf 
[root@localhost opt]# echo then >> httpd.conf 
[root@localhost opt]# sed -ne '/the/p' httpd.conf 
the this is test
the
then
[root@localhost opt]# sed -ne '/\<the\>/p' httpd.conf 
the this is test
the

4.3.2 删除符合条件的文本(d)

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

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

  • 删除第三行
[root@localhost opt]# nl httpd.conf 
     1  #
     2  # This is the main Apache HTTP server configuration file.  It contains the
     3  # configuration directives that give the server its instructions.
     4  # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
     5  # In particular, see 
[root@localhost opt]# nl httpd.conf | sed '3d'
     1  #
     2  # This is the main Apache HTTP server configuration file.  It contains the
     4  # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
     5  # In particular, see 

  • 删除1到5行
[root@localhost opt]# sed '1,5d' httpd.conf 
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
[root@localhost opt]# nl httpd.conf | sed '1,5d'
     6  # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
     7  # for a discussion of each configuration directive.
     8  #
     9  # Do NOT simply read the instructions in here without understanding

  • 删除包含the 的行
[root@localhost opt]# nl httpd.conf | sed '/the/d'
     1  #
     4  # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
     5  # In particular, see 
     6  # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>

  • 删除以#为开头的行
[root@localhost opt]# sed -ne '/#/d' httpd.conf 
[root@localhost opt]# echo $?
0
[root@localhost opt]# sed -ne '/\#/d' httpd.conf 
[root@localhost opt]# echo $?
0
[root@localhost opt]# sed -ne '/\#/d' httpd.conf | nl
[root@localhost opt]# nl httpd.conf | sed -ne '/#/d'
[root@localhost opt]# nl httpd.conf | sed -ne '/\#/d'
[root@localhost opt]# nl httpd.conf | sed '/\#/d'
<Directory "/var/www/html">
    Options Indexes FollowSymLinks

    AllowOverride None
[root@localhost opt]# sed '/^#/d' httpd.conf 
<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:

  • 删除以w为开头的行(也可以删除以数字为开头’/2/d’)
[root@localhost opt]# sed -ne '/^wo/d' httpd.conf 
[root@localhost opt]# echo $?
0
[root@localhost opt]# sed '/^wo/d' httpd.conf 
the this is test
w  d
tast
qxyzxyzxyzxyzs

可以发现,使用d删除的时候,如果使用-n,表示仅显示处理后的结果。但是因为修改的已经被删掉,所以显示为空,使用d时,不要加-n

  • 删除以 . 为结尾的行
[root@localhost opt]# nl httpd.conf | sed '/\.$/d'
     1  #
     2  # This is the main Apache HTTP server configuration file.  It contains the
     5  # In particular, see 
     6  # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
     8  #


  • 删除空行
[root@localhost opt]# nl httpd.conf | sed '/^$/d'

333  qxyqzcyzs
334                     
       
       
       
       
       
       
       
       
       
       
335  the
336  then
[root@localhost opt]# sed -e '/^$/d' httpd.conf 
qxyzqxyzs
qxyqzcyzs
                   
the
then

  • 空行指的是回车后的行,空格存在的行并不会被删除

注意: 若是删除重复的空行,即连续的空行只保留一个, 执行“ sed –e ‘/^KaTeX parse error: Expected group after '^' at position 6: /{n;/^̲/d}’test.txt”命令即可实现。其效果与“cat -s test.txt”相同,n 表示读下一行数据。

[root@localhost opt]# sed -e '/^$/{n;/^$/d}' httpd.conf 

4.3.3 替换符合条件的文本

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

sed ‘s/the/THE/’ test.txt //将每行中的第一个the 替换为 THE

sed ‘s/l/L/2’ test.txt //将每行中的第 2 个l 替换为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

  • sed ‘s/the/THE/’ test.txt //将每行中的第一个the 替换为 THE
  • sed ‘s/the/THE/g’ test.txt //将文件中的所有the 替换为THE
[root@localhost opt]# sed -e 's/the/THE/' httpd.conf 
#
# This is THE main Apache HTTP server configuration file.  It contains the
# configuration directives that give THE server its instructions.

[root@localhost opt]# sed -e 's/the/THE/g' httpd.conf 
#
# This is THE main Apache HTTP server configuration file.  It contains THE
# configuration directives that give THE server its instructions.

[root@localhost opt]# sed -en 's/the/THE/g' httpd.conf 
sed: can't read s/the/THE/g: No such file or directory

[root@localhost opt]# sed -ne 's/the/THE/g' httpd.conf 
[root@localhost opt]# echo $?
0

  • sed ‘s/l/L/2’ test.txt //将每行中的第 2 个l 替换为L
[root@localhost opt]# sed -e 's/l/L/2' httpd.conf 
l L l l l l l 
l L l l l l l
l L l l l l l 
l L l l l l l
l L l l l l l 
l L l l l l l
[root@localhost opt]# nl httpd.conf | sed -e 's/l/L/2'
   335  l L l l l l l 
   336  l L l l l l l
   337  l L l l l l l 
   338  l L l l l l l
   339  l L l l l l l 
   340  l L l l l l l

  • sed **‘s/o/ /g’ test.txt //将文件中的所有o 删除(替换为空串)
[root@localhost opt]# nl httpd.conf | sed 's/o//g'
     1  #
     2  # This is the main Apache HTTP server cnfiguratin file.  It cntains the
     3  # cnfiguratin directives that give the server its instructins.
     4  # See <URL:http://httpd.apache.rg/dcs/2.4/> fr detailed infrmatin.

  • sed **'s/^/#/ ’ test.txt //在每行行首插入#号
[root@localhost opt]# nl httpd.conf | sed 's/^/777/'
777     1       #
777     2       # This is the main Apache HTTP server configuration file.  It contains the
777     3       # configuration directives that give the server its instructions.
777     4       # See <URL:http://httpd.apache.org/docs/2.4/> for detailed informatio
[root@localhost opt]# sed 's/^/777/' httpd.conf 
777#
777# This is the main Apache HTTP server configuration file.  It contains the
777# configuration directives that give the server its instructions.
777# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.

  • sed ‘/the/s/^/#/’ test.txt //在包含the 的每行行首插入#号
[root@localhost opt]# sed -e '/the/ s/^/777/' httpd.conf 
#
777# This is the main Apache HTTP server configuration file.  It contains the
777# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.

  • sed** ‘s/$/EOF/’ test.txt //在每行行尾插入字符串EOF
[root@localhost opt]# sed -e '/the/ s/$/777/' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the777
# configuration directives that give the server its instructions.777
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
[root@localhost opt]# sed -e '/the/ s/$/777/!' httpd.conf 
sed: -e expression #1, char 15: unknown option to `s'
[root@localhost opt]# sed -e '/the/! s/$/777/' httpd.conf 
#777
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.777
  • sed** ‘3,5s/the/THE/g’ test.txt //将第 3~5 行中的所有the 替换为 THE
[root@localhost opt]# sed -e '356,360 s/o/t/g' httpd.conf 
wd
wtd
wttd
wtttd
wttttttttd


测试时发现使用nl 命令去查看行号,与vim 中实际的行号有出入,涉及到具体的行号还是以vim 为主

  • sed **’/the/s/o/O/g’ **test.txt //将包含the 的所有行中的o 都替换为 O
[root@localhost opt]# nl httpd.conf | sed -e '/the/ s/o/O/g'
     1  #
     2  # This is the main Apache HTTP server cOnfiguratiOn file.  It cOntains the
     3  # cOnfiguratiOn directives that give the server its instructiOns.
     4  # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.

4.3.4 迁移符合条件的文本 (即剪切)

其中,

  • H,复制到剪贴板;
  • g、将剪贴板中的数据覆盖至指定行;
  • G,将剪贴板中的数据追加至指定行;
  • w,保存为文件;
  • r,读取指定文件;
  • a,追加指定内容。

sed ‘/the/{H;d};$G’ test.txt //将包含the 的行迁移至文件末尾,{;}用于多个操作

sed ‘1,5{H;d};17G’ 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 表示换行

  • sed ‘/the/{H;d};$G’ test.txt //将包含the 的行迁移至文件末尾,{;}用于多个操作
[root@localhost opt]# sed '/#/{H;d};$G' httpd.conf 

ServerRoot "/etc/httpd"
then

#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.

  • sed ‘1,5{H;d};17G’ test.txt //将第 1~5 行内容转移至第 17 行后
[root@localhost opt]# nl httpd.conf | sed '1,4{H;d};5G'
     5  # In particular, see 

     1  #
     2  # This is the main Apache HTTP server configuration file.  It contains the
     3  # configuration directives that give the server its instructions.
     4  # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
     6  # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>

  • sed '/the/w out.file’ test.txt //将包含the 的行另存为文件out.file
[root@localhost opt]# sed '/the/w out.file' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
[root@localhost opt]# ls
httpd.conf  jb.list  jbxx  out.file  rh
[root@localhost opt]# vim out.file 

  • sed '/the/r /etc/hostname’ test.txt //将文件/etc/hostname 的内容添加到包含the 的每行以后
[root@localhost opt]# sed '/the/r /etc/hostname' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
localhost.localdomain
# configuration directives that give the server its instructions.
localhost.localdomain

sed ‘3aNew’ test.txt //在第 3 行后插入一个新行,内容为 New

[root@localhost opt]# sed '2a qqqqqqqqqqqqqqqq' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
qqqqqqqqqqqqqqqq
# configuration directives that give the server its instructions.

sed ‘/the/aNew’ test.txt //在包含the 的每行后插入一个新行,内容为 New

[root@localhost opt]# sed '/\<the\>/a wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
# configuration directives that give the server its instructions.
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww

sed ‘3aNew1\nNew2’ test.txt //在第 3 行后插入多行内容,中间的\n 表示换行

[root@localhost opt]# sed '3awwwwwwwwwwwwwwwww\nwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
wwwwwwwwwwwwwwwww
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww

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

4.3.5 使用脚本编辑文件 -f

使用 sed 脚本,将多个编辑指令存放到文件中(每行一条编辑指令),通过“-f”选项来调用。例如:

[root@localhost opt]# vim jb.list
[root@localhost opt]# cat jb.list 
1,5H    //H复制到粘贴板
1,5d    //d把1,5行删掉
6G      //粘贴到第六行后
[root@localhost opt]# nl httpd.conf | sed -f jb.list
     6  # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>

     1  #
     2  # This is the main Apache HTTP server configuration file.  It contains the
     3  # configuration directives that give the server its instructions.
     4  # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
     5  # In particular, see 
     7  # for a discussion of each configuration directive.

4.3.6 sed 直接操作文件示例

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

[root@localhost ~]# vim local_only_ftp.sh 
#!/bin/bash
# 指定样本文件路径、配置文件路径
SAMPLE="/usr/share/doc/vsftpd-3.0.2/EXAMPLE/INTERNET_SITE/vsftpd.conf " CONFIG="/etc/vsftpd/vsftpd.conf"
# 备份原来的配置文件,检测文件名为/etc/vsftpd/vsftpd.conf.bak 备份文件是否存在, 
#若不存在则使用 cp 命令进行文件备份
[ ! -e "$CONFIG.bak" ] && cp $CONFIG $CONFIG.bak 
# 基于样本配置进行调整,覆盖现有文件
sed -e '/^anonymous_enable/s/YES/NO/g' $SAMPLE > $CONFIG
sed -i -e '/^local_enable/s/NO/YES/g' -e '/^write_enable/s/NO/YES/g' $CONFIG grep "listen" $CONFIG || sed -i '$alisten=YES' $CONFIG
# 启动vsftpd 服务,并设为开机后自动运行
systemctl restart vsftpd
systemctl enable vsftpd
[root@localhost ~]# chmod +x local_only_ftp.sh

五 :awk工具

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

5.1 awk 常见用法

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

awk 选项 '模式或条件 {编辑指令}' 文件 1 文件 2 „	
//过滤并输出文件符条件的内容
awk -f 脚本文件 文件 1 文件 2 „	
//从脚本中调用编辑指令,过滤并输出内容
前面提到 sed 命令常用于一整行的处理,而 awk 比较倾向于将一行分成多个“字段”然后再进行处理,且默认情况下字段的分隔符为空格或者 tab 键。awk 执行结果可以通过 print 的功能将字段数据打印显示。

​ 在使用 awk 命令的过程中,可以使用逻辑操作符“&&”,表示“与”, “||”表示“或”,“!”表示“非”;还可以进行简单的数学运算,如+、-、*、/、%、^分别 表示加、减、乘、除、取余和乘方。

​ 在 Linux 系统中/etc/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
„„//省略部分内容

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1X7QozjH-1575383336844)(G:\GSY\Documents\typora图片\1575361781262.png)]

5.2 awk 包含几个特殊的内建变量(可直接用)

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

5.3 用法示例

5.3.1 按行输出文本

  • awk ‘{print}’ httpd.conf //输出所有内容,等同于cat test.txt
[root@localhost opt]# awk '{print}' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 

awk ‘{print $0}’ httpd.conf //输出每行内容,等同于cat test.txt

[root@localhost opt]# awk '{print $0}' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 

awk ‘NR1,NR3{print}’ httpd.conf //输出第1-3行内容

[root@localhost opt]# awk 'NR==1,NR==3{print}' httpd.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.

awk ‘(NR=>1)&&(NR<=3){print}’ httpd.conf //输出第1-3行内容

[root@localhost opt]# awk '(NR>=1)&&(NR<=3){print}' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

awk ‘NR1||NR3{print}’ httpd.conf //输出第一行、第三行内容

[root@localhost opt]# awk 'NR==1||NR==3{print}' httpd.conf 
#
# configuration directives that give the server its instructions.

awk ‘(NR%2)==1{print}’ httpd.conf //输出奇数行的内容

[root@localhost opt]# awk '(NR%2)==1{print}' httpd.conf 
#
# configuration directives that give the server its instructions.
# In particular, see 
# for a discussion of each configuration directive.

awk ‘(NR%2)==0{print}’ httpd.conf //输出偶数行内容

awk 输出奇偶数行时,是绝对的,sed是相对的

[root@localhost opt]# awk '(NR%2)==0{print}' httpd.conf 
# This is the main Apache HTTP server configuration file.  It contains the
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
#

awk ‘/^root/{print}’ /etc/passwd //输出以root为开头的行

[root@localhost opt]# awk '/^root/{print}' /etc/passwd
root:x:0:0:root:/root:/bin/bash

输出包含/bin/bash的行

[root@localhost opt]# awk '/\/bin\/bash/{print}' /etc/passwd
root:x:0:0:root:/root:/bin/bash
gsy:x:1000:1000:gsy:/home/gsy:/bin/bash

awk ‘/bash$/{print}’ /etc/passwd //输出以bash为结尾的行

[root@localhost opt]# awk '/bash$/{print}' /etc/passwd
root:x:0:0:root:/root:/bin/bash
gsy:x:1000:1000:gsy:/home/gsy:/bin/bash

awk 'BEGIN{x=0};//bin/bash / x + + ; E N D p r i n t x / e t c / p a s s w d / / / b i n / b a s h g r e p c / b i n . b a s h / x++;END{print x}' /etc/passwd //统计以/bin/bash结尾的行数,效果等同于grep -c ”/bin.bash “ /etc/passwd

[root@localhost opt]# awk '/\/bin\/bash/{print | "wc -l"}' /etc/passwd
2
[root@localhost opt]# awk '/\/bin\/bash$/{n++};END{print n}' /etc/passwd
2
[root@localhost opt]# awk 'BEGIN{N=0}; /\/bin\/bash$/{n++};END{print n}' /etc/passwd
2
[root@localhost opt]# grep -c "/bin/bash$" /etc/passwd
2

awk ‘BEGIN{RS=” “};END{print NR}’ test.txt //统计以空行为分隔的段落数

[root@localhost opt]# awk 'BEGIN{RS=" "};END{print NR}' httpd.conf 
2101

RS为空行的意思,NR是为段落

5.3.2 按字段输出文本

awk -F: ‘{print $1}’ /etc/passwd //以:为分隔符,去检索每行的第一字段 若是以空格或者制表符为分隔符,可以不用追加-F

[root@localhost opt]# awk -F: '{print $1}' /etc/passwd 
root
bin
daemon
adm
lp

awk -F: ‘$2==" "{print}’ /etc/shadow //输出第二行为空的行,即输出密码为空的用户的shadow记录

[root@localhost opt]# awk -F: 'NR==1,NR==5{print $1}' /etc/passwd 
root
bin
daemon
adm
lp

awk ‘BEGIN{FS=":"};$2=="!!"{print}’ /etc/shadow //输出没有密码的用户

[root@localhost opt]# awk 'BEGIN{FS=":"};$2=="!!"{print $1}' /etc/shadow
systemd-network
dbus
polkitd
abrt
libstoragemgmt
rpc
…………

条件的等于号是两个

[root@localhost opt]# awk -F: '$2="*"{print $1}' /etc/shadow
root
bin
daemon
adm
lp
sync
shutdown
[root@localhost opt]# awk -F: '$2=="*"{print $1}' /etc/shadow
bin
daemon
adm
lp
sync
shutdown

[root@localhost opt]# cat /etc/shadow
root:$6$lZy/ZqchdBxv/dZ0$RUyTDADN9e2H0hJlb9J757GyZ0nxWhPKY1sDdyCtvBR2/Asw/CPCAFFIfJB.kO7qbicMQx1LeoP53Xq/YXJeC0::0:99999:7:::
bin:*:17110:0:99999:7:::
daemon:*:17110:0:99999:7:::
adm:*:17110:0:99999:7:::
lp:*:17110:0:99999:7:::
sync:*:17110:0:99999:7:::

以冒号为分隔符、第七字段包含/bash的行,将符合条件的行的第一字段输出,这个可以输出可登录的用户

[root@localhost opt]# awk 'BEGIN{FS=":"};$7~"/bash"{print $1}' /etc/passwd
root
gsy

以一行八个字段、而且第一字段包含nfs的行,将符合条件的行的第一字段和第二字段输出

[root@localhost opt]# awk '(NF==8)&&($1~"nfs"){print $1,$2}' /etc/services 
nfs 2049/tcp
nfs 2049/udp
nfs 2049/sctp
netconfsoaphttp 832/tcp
netconfsoaphttp 832/udp
netconfsoapbeep 833/tcp
netconfsoapbeep 833/udp

awk -F “:” '($7!="/bin/bash")&&($7!="/sbin/nologin"){print}’ /etc/passwd //输出第 7 个字段既不为/bin/bash 也不为/sbin/nologin 的所有行

[root@localhost opt]# awk -F: '($7!="/bin/bash")&&($7!="/sbin/nologin"){print}' /etc/passwd
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
[root@localhost opt]# awk -F: '($7!~"/bin/bash")&&($7!~"/sbin/nologin"){print}' /etc/passwd
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt

大括号里面是操作,外面是条件

awk中~指的是包含,包含的字符串需要使用双引号引出来

5.3.3 通过管道符号、双引号调用shell命令

awk -F: ‘/bash$/{print | “wc -l”}’ /etc/passwd

//调用wc -l 命令统计使用bash 的用户个数,等同于 grep -c “bash$” /etc/passwd

awk 'BEGIN {while (“w” | getline) n++ ; {print n-2}}'

//调用w 命令,并用来统计在线用户数

awk 'BEGIN { “hostname” | getline ; print $0}'

//调用hostname,并输出当前的主机名

  • awk -F: ‘/bash$/{print | “wc -l”}’ /etc/passwd**

//调用wc -l 命令统计使用bash 的用户个数,等同于 grep -c “bash$” /etc/passwd

[root@localhost opt]# awk -F: '$7~"bash$"{print | "wc -l"}' /etc/passwd
2
[root@localhost opt]# awk '/bash$/{print | "wc -l"}' /etc/passwd
2

  • awk 'BEGIN {while (“w” | getline) n++ ; {print n-2}}'

//调用w 命令,并用来统计在线用户数

在BEGNIN中,可以引用条件语句

没有定义值时,默认从零开始

[root@localhost ~]# awk 'BEGIN {while("w" | getline) n++;{print n-2}}'
4

awk 'BEGIN { “hostname” | getline ; print $0}'

//调用hostname,并输出当前的主机名

[root@localhost ~]# awk 'BEGIN{"hostname" | getline;print $0}'
localhost.localdomain
[root@localhost ~]# awk -F. 'BEGIN{"hostname" | getline;print $1}'
localhost

六 :sort 工具

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

​ sort 是一个以行为单位对文件内容进行排序的工具,也可以根据不同的数据类型来排序。例如数据和字符的排序就不一样。

  • sort 命令的语法为“sort [选项] 参数”
  • 其中常用的选项包括以下几种

6.1 sort 选项

  • -f:忽略大小写;

  • -b:忽略每行前面的空格;

  • -M:按照月份进行排序;

  • -n:按照数字进行排序;

  • -r:反向排序;

  • -u:等同于 uniq,表示相同的数据仅显示一行;

  • -t:指定分隔符,默认使用[Tab]键分隔;

  • -o <输出文件>:将排序后的结果转存至指定文件;

  • -k:指定排序区域。

6.2 示例

  • cat /etc/passwd
[root@localhost ~]# cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

  • sort /etc/passwd //默认按每行的首字母进行排序
[root@localhost ~]# sort /etc/passwd
abrt:x:173:173::/etc/abrt:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
bin:x:1:1:bin:/bin:/sbin/nologin
chrony:x:995:991::/var/lib/chrony:/sbin/nologin

  • sort -t “:” -rk 3 /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
libstoragemgmt:x:998:996:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin
colord:x:997:995:User for colord:/var/lib/colord:/sbin/nologin
saslauth:x:996:76:Saslauthd user:/run/saslauthd:/sbin/nologin

  • sort -t: -k 3 /etc/paswd -o /opt/111
[root@localhost ~]# sort -t: -k 3 /etc/passwd -o /opt/111
[root@localhost ~]# echo $?
0
[root@localhost opt]# cat 111
root:x:0:0:root:/root:/bin/bash
gsy:x:1000:1000:gsy:/home/gsy:/bin/bash
qemu:x:107:107:qemu user:/:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin

七 : uniq 工具

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

7.1 常用选项

  • -c:进行计数;

  • -d:仅显示重复行;

  • -u:仅显示出现一次的行;

7.2 示例

[root@localhost ~]# cat testfile 
Linux 10
Linux 20
Linux 30
Linux 30
Linux 30
CentOS 6.5
CentOS 6.5
CentOS 6.5
CentOS 7.3
CentOS 7.3
CentOS 7.3
  • 删除 testfile 文件中的重复行。
[root@localhost ~]# uniq testfile 
Linux 10
Linux 20
Linux 30
CentOS 6.5
CentOS 7.3
  • 删除 testfile 文件中的重复行,并在行首显示该行重复出现的次数。
[root@localhost ~]# uniq -c testfile 
1 Linux 10
1 Linux 20
3 Linux 30
3 CentOS 6.5
3 CentOS 7.3
  • 查找 testfile 文件中的重复行,即只查看文件中的重复行
[root@localhost ~]# uniq -d testfile 
Linux 30
CentOS 6.5
CentOS 7.3

/nologin
avahi❌70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
bin❌1:1:bin:/bin:/sbin/nologin
chrony❌995:991::/var/lib/chrony:/sbin/nologin


- sort -t ":" -rk 3 /etc/passwd	//把文件中以:为分隔的第三列作为基础进行反向排序

[root@localhost ~]# sort -t: -rk 3 /etc/passwd
nobody❌99:99:Nobody:/:/sbin/nologin
polkitd❌999:998:User for polkitd:/:/sbin/nologin
libstoragemgmt❌998:996:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin
colord❌997:995:User for colord:/var/lib/colord:/sbin/nologin
saslauth❌996:76:Saslauthd user:/run/saslauthd:/sbin/nologin


- sort -t: -k  3 /etc/paswd -o /opt/111

[root@localhost ~]# sort -t: -k 3 /etc/passwd -o /opt/111
[root@localhost ~]# echo $?
0
[root@localhost opt]# cat 111
root❌0:0:root:/root:/bin/bash
gsy❌1000:1000:gsy:/home/gsy:/bin/bash
qemu❌107:107:qemu user:/:/sbin/nologin
operator❌11:0:operator:/root:/sbin/nologin


# 七 : uniq 工具

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

## 7.1 常用选项

- -c:进行计数;

- -d:仅显示重复行;

- -u:仅显示出现一次的行;

## 7.2 示例

[root@localhost ~]# cat testfile
Linux 10
Linux 20
Linux 30
Linux 30
Linux 30
CentOS 6.5
CentOS 6.5
CentOS 6.5
CentOS 7.3
CentOS 7.3
CentOS 7.3




- 删除 testfile 文件中的重复行。

[root@localhost ~]# uniq testfile
Linux 10
Linux 20
Linux 30
CentOS 6.5
CentOS 7.3


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

[root@localhost ~]# uniq -c testfile
1 Linux 10
1 Linux 20
3 Linux 30
3 CentOS 6.5
3 CentOS 7.3


- 查找 testfile 文件中的重复行,即只查看文件中的重复行

[root@localhost ~]# uniq -d testfile
Linux 30
CentOS 6.5
CentOS 7.3



  1. ^a-zA-Z ↩︎

  2. 0-9 ↩︎

发布了87 篇原创文章 · 获赞 26 · 访问量 4556

猜你喜欢

转载自blog.csdn.net/Lfwthotpt/article/details/103378009