Shell 基础---正则表达式与文本处理器--(grep,egrep 与文本处理器-sed、awk、sort、uniq、tr)

Shell 编程之正则表达式与文本处理器--(grep,egrep 与文本处理器-sed、awk、sort、uniq、tr)

文章目录

一、正则表达式

1.1 正则表达式概述

1.1.1 正则表达式的定义

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

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

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

1.1.2 正则表达式用途

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

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

1.2 基础正则表达式

  • 正则表达式的字符串表达方法根据不同的严谨程度与功能分为基本正则表达式与扩展正则表达式。
  • 基础正则表达式是常用正则表达式最基础的部分。
  • 在 Linux 系统中常见的文件处理工具中 grep 与 sed 支持基础正则表达式,而 egrep 与 awk 支持扩展正则表达式。

1.3 基础正则表达式:grep命令

下面的操作需要提前准备一个名为 httpd.conf 的测试文件

[root@localhost conf]# yum install httpd -y
[root@localhost conf]# cp /etc/httpd/conf/httpd.conf /opt
cp:是否覆盖"/opt/httpd.conf"? yes
[root@localhost conf]# cd /opt

1.3.1 查找特定字符

  • “-n”表示显示行号

  • “-i”表示不区分大小写

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

  • 从 httpd.conf 文件中查找出特定字符“the” 所在位置

[root@localhost opt]# grep -n 'the' httpd.conf
  •  

在这里插入图片描述
只显示行号,后面加管道符合和awk

[root@localhost opt]# grep -n 'the' httpd.conf | awk -F: '{print $1}'
  • 1

在这里插入图片描述
统计行号:

[root@localhost opt]# grep -n 'the' httpd.conf | wc -l
64
  • 从 /etc/passwd文件中查找出特定字符“the” 所在位置,不区分大小写
[root@localhost opt]# grep -in 'the' httpd.conf

在这里插入图片描述
若反向选择,如查找不包含“the”字符的行,则需要通过 grep 命令的“-v”选项实现,并配合“-n”一起使用显示行号

[root@localhost opt]# grep -vn 'the' httpd.conf

在这里插入图片描述

1.3.2 利用中括号“[]”来查找集合字符

  • 想要查找“this”与“thes”这两个字符串时,可以发现这两个字符串均包含“hi” 与“he”

  • “[]”中无论有几个字符,都仅代表一个字符,也就是说“[ie]”表示匹配“i”或者“e”

  • 同时查找到“this”与“thes”这两个字符串

[root@localhost opt]# grep -n 'th[ie]s' httpd.conf

在这里插入图片描述
若要查找包含重复单个字符“oo”时,只需要执行以下命令即可。
先在httpd.conf 的末尾加上这几行
在httpd.conf 的末尾加上这几行

[root@localhost opt]# grep -n 'oo' httpd.conf 

在这里插入图片描述

  • 若查找“oo”前面不是“w”的字符串,只需要通过集合字符的反向选择“[^]”来实现该目的。
  • 例如执行“grep -n‘[^w]oo’httpd.conf ”命令表示在 httpd.conf 文本中查找“oo”前面不是“w”的字符串。
[root@localhost opt]# grep -n '[^w]oo' httpd.conf 

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

当^符号放在[ ]外面时,表示以什么为开头;
以小写字母为开头:

[root@localhost opt]# grep -n '^[a-z]' httpd.conf 
354:wd
355:wod
356:wood
357:woood
358:wooood
359:woooood

在这里插入图片描述
以字母为开头的,不区分大小写:

[root@localhost opt]# grep -n '^[a-zA-Z]' httpd.conf 
31:ServerRoot "/etc/httpd"
42:Listen 80
56:Include conf.modules.d/*.conf
66:User apache
67:Group apache
86:ServerAdmin root@localhost
119:DocumentRoot "/var/www/html"
182:ErrorLog "logs/error_log"
189:LogLevel warn
316:AddDefaultCharset UTF-8
348:EnableSendfile on
353:IncludeOptional conf.d/*.conf
354:wd
355:wod
356:wood
357:woood
358:wooood
359:woooood

在这里插入图片描述
当^符号放在[ ]里面时,表示取反,不以什么为开头
把不是以0-9的行显示出来

[root@localhost opt]# grep -n '[^0-9]' httpd.conf

在这里插入图片描述
查找包含数字的行:

[root@localhost opt]# grep -n '[0-9]' httpd.conf 

在这里插入图片描述

grep -nv ‘[0-9]’ http.conf
输出的行不会有数字
只要行有数字,就不匹配

grep -n ‘[^0-9]’ http.conf
过滤:
只要不是数字,其他的都能匹配上,输出所有字符

1.3.3 查找行首“^”与行尾字符“$”

  • 基础正则表达式包含两个定位元字符:“^”(行首)与“$”(行尾)。
  • 如果想要查询以“root”字符串为行首的行,则可以通过“^”元字符来实现。
[root@localhost opt]# grep -n '^root' /etc/passwd
1:root:x:0:0:root:/root:/bin/bash

查询以数字为结尾的行

[root@localhost opt]# grep -n '[0-9]$' /opt/httpd.conf 
41:#Listen 12.34.56.78:80
42:Listen 80
95:#ServerName www.example.com:80
316:AddDefaultCharset UTF-8

查询空白行 (^$)

[root@localhost opt]# grep -n '^$' httpd.conf 
20:
32:
43:
57:
68:
80:
87:

以小写字母为开头:

[root@localhost opt]# grep -n '^[a-z]' httpd.conf 
354:wd
355:wod
356:wood
357:woood
358:wooood
359:woooood

在这里插入图片描述
查询大写字母开头的行则使用’^ [A-Z]'规则

[root@localhost opt]# grep -n '^[A-Z]' httpd.conf 
31:ServerRoot "/etc/httpd"
42:Listen 80
56:Include conf.modules.d/*.conf
66:User apache
67:Group apache
86:ServerAdmin root@localhost
119:DocumentRoot "/var/www/html"
182:ErrorLog "logs/error_log"
189:LogLevel warn
316:AddDefaultCharset UTF-8
348:EnableSendfile on
353:IncludeOptional conf.d/*.conf

查询不以字母开头的行则使用“ ^ [^a-zA-Z]”规则

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

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

[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'.
23:# configuration, error, and log files are kept.
29:# least PidFile.
36:# directive.
......

在这里插入图片描述

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

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

查找“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:
356:wood

在这里插入图片描述
在上述结果中,“wood”字符串“w…d”匹配规则。

若想要查询 oo、ooo、ooooo 等资料, 则需要使用星号元字符 * 。但需要注意的是,“ * ”代表的是重复零个或多个前面的单字符。

“ o* ”表示拥有零个(即为空字符)或大于等于一个“o”的字符,因为允许空字符,所以执行“grep -n ‘o*’ httpd.conf”命令会将文本中所有的内容都输出打印。

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

同理,若查询包含至少两个 o 以上的字符串,则执行“grep -n ‘ooo*’ httpd.conf”命令即可。

[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
22:# ServerRoot: The top of the directory tree under which the server's
26:# ServerRoot at a non-local disk, be sure to specify a local disk on the
28:# same ServerRoot for multiple httpd daemons, you will need to change at
31:ServerRoot "/etc/httpd"
54:# LoadModule foo_module modules/mod_foo.so
60:# httpd as root initially and it will switch.  
63:# It is usually good practice to create a dedicated user and group for
86:ServerAdmin root@localhost
115:# DocumentRoot: The directory out of which you will serve your
119:DocumentRoot "/var/www/html"
130:# Further relax access to the default document root:
226:    # Redirect permanent /foo http://www.example.com/bar
230:    # access content that does not live under the DocumentRoot.
332:#ErrorDocument 500 "The server made a boo boo."
356:wood
357:woood
358:wooood
359:woooood

在这里插入图片描述
查询以 w 开头 d 结尾,中间包含至少一个 o 的字符串,执行以下命令即可实现。

[root@localhost opt]# grep -n 'woo*d' httpd.conf   '表示*前面的o出现0次或者多次,与另外一个o无关'
355:wod
356:wood
357:woood
358:wooood
359:woooood

在这里插入图片描述
*
表示前面的字符出现0次或多次,( * 前面字符的前面的其他字符无关,该是几个还是几个)
. * 任意前面的字符

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

[root@localhost opt]# grep -n 'w.*d' httpd.conf
......
354:wd
355:wod
356:wood
357:woood
358:wooood
359:woooood

在这里插入图片描述
执行以下命令即可查询任意数字所在行
grep -n ‘[0-9][0-9]*’ httpd.conf (前面包含有数字,数字后面数字可有可无)

[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>
14:# of the server's control files begin with "/" (or "drive:/" for Win32), the
41:#Listen 12.34.56.78:80
42:Listen 80
95:#ServerName www.example.com:80
......

在这里插入图片描述
若* 前面不带任何字符参考, * 就作为一个普通字符,表示就过滤 *

[root@localhost opt]# grep -n '*' httpd.conf 
15:# server will use that explicit path.  If the filenames do *not* begin
56:Include conf.modules.d/*.conf
137:    # Note that "MultiViews" must be named *explicitly* --- "Options All"
171:<Files ".ht*">
179:# logged here.  If you *do* define an error logfile for a <VirtualHost>
207:    # container, they will be logged here.  Contrariwise, if you *do*
209:    # logged therein and *not* in this file.
353:IncludeOptional conf.d/*.conf

在这里插入图片描述

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

限定范围的字符“{}”,在 Shell 中具有特殊意义,在使用“{}”字符时,需要利用转义字符“\”,将“{}”字符转换成普通字符。

  • 查询两个 o 的字符
[root@localhost opt]# grep -n 'o\{2\}' httpd.conf 

在这里插入图片描述

  • 查询以 w 开头以 d 结尾,中间包含 2~5 个 o 的字符串
[root@localhost opt]# grep -n 'wo\{2,5\}d' httpd.conf 
356:wood
357:woood
358:wooood
359:woooood
  • 查询以 w 开头以 d 结尾,中间包含 2 个或 2 个以上 o 的字符串
[root@localhost opt]# grep -n 'wo\{2,\}d' httpd.conf 
356:wood
357:woood
358:wooood
359:woooood

先匹配满5个,再匹配后面的
在这里插入图片描述
在这里插入图片描述

1.4 元字符总结

元字符 作用
^ 匹配输入字符串的开始位置。除非在方括号表达式中使用,表示不包含该字符集合。要匹配“^” 字符本身,请使用“\ ^”,在方括号外面表示以什么为开头
$ 匹配输入字符串的结尾位置。如果设置了RegExp 对象的 Multiline 属性,则“$”也匹配‘\n’或‘\r’。要匹配“ $ ”字符本身,请使用“\ $”
. 匹配除“\r\n”之外的任何单个字符
\ 反斜杠,又叫转义字符,去除其后紧跟的元字符或通配符的特殊意义
* 匹配前面的子表达式零次或多次。要匹配“*”字符,请使用“ \ * ”
[] 字符集合。匹配所包含的任意一个字符。例如,“[abc]”可以匹配“plain”中的“a”
[^] 赋值字符集合。匹配未包含的一个任意字符。例如,“[^abc]”可以匹配“plain”中任何一个字母
[n1-n2] 字符范围。匹配指定范围内的任意一个字符。例如,“[a-z]”可以匹配“a”到“z”范围内的任意一个小写字母字符。注意:只有连字符(-)在字符组内部,并且出现在两个字符之间时,才能表示字符的范围;如果出现在字符组的开头,则只能表示连字符本身
{n} n 是一个非负整数,匹配确定的 n 次。例如,“o{2}”不能匹配“Bob”中的“o”,但是能匹配“food”中的“oo”
{n,} n 是一个非负整数,至少匹配 n 次。例如,“o{2,}”不能匹配“Bob”中的“o”,但能匹配“foooood”中的所有o。“o{1,}”等价于“o+”。“o{0,}”则等价于“o*”
{n,m} m 和 n 均为非负整数,其中 n<=m,最少匹配 n 次且最多匹配m 次

“” 和 ‘’ 不做区分
shell脚本中:“”中要加变量,‘’只是字符

二、扩展正则表达式

  • 过滤除文件中空白行与行首为“#”之外的行(通常用于查看生效的配置文件),执行“grep -v ‘^$’ httpd.conf | grep -v ‘^#’”即可实现。这里需要使用管道命令来搜索两次。

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

  • 此外,grep 命令仅支持基础正则表达式,如果使用扩展正则表达式,需要使用 egrep 或 awk 命令。

  • egrep 命令与 grep 命令的用法基本相似

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

过滤除文件中空白行与行首为“#”之外的行(通常用于查看生效的配置文件)

[root@localhost opt]# grep -vn '^$' httpd.conf | grep -vn '^#'  

或者
使用扩展正则表达式

[root@localhost opt]# egrep -v '^$|^#' httpd.conf 

扩展正则表达式常见元字符

元字符 作用于示例
+ 作用:重复一个或者一个以上的前一个字符 。示例:执行“egrep -n ‘wo+d’ httpd.conf”命令,即可查询"wood" “woood” "woooooood"等字符串
作用:零个或者一个的前一个字符。 示例:执行“egrep -n ‘bes?t’ httpd.conf”命令,即可查询“bet”“best”这两个字符串
l 作用:使用或者(or)的方式找出多个字符。 示例:执行“egrep -n ‘of l is l on’ httpd.conf“ 命令即可查询"of"或者"if"或者"on"字符串
() 作用:查找“组”字符串。 示例:“egrep -n ‘t(ale)st’ httpd.conf”。“tast”与“test”因为这两个单词的“t”与“st”是重复的,所以将“a”与“e”列于“()”符号当中,并以“
()+ 作用:辨别多个重复的组。 示例:“egrep -n ‘A(xyz)+C’ httpd.conf”。该命令是查询开头的"A"结尾是"C",中间有一个以上的 "xyz"字符串的意思

过滤出一个及一个以上的o:
扩展表达式

[root@localhost opt]# egrep -n 'wo+d' httpd.conf 
356:wod
357:wood
358:woood
359:wooood
360:woooood
361:woooooood
362:woooooooooood

基础表达式

[root@localhost opt]# grep -n 'woo*d' httpd.conf 
356:wod
357:wood
358:woood
359:wooood
360:woooood
361:woooooood
362:woooooooooood

大括号{}形式:

[root@localhost opt]# grep -n 'wo\{1,\}d' httpd.conf 
356:wod
357:wood
358:woood
359:wooood
360:woooood
361:woooooood
362:woooooooooood

过滤出0个或者一个o
egrep:

[root@localhost opt]# egrep -n 'wo?d' httpd.conf 
168:# The following lines prevent .htaccess and .htpasswd files from being 
355:wd
356:wod

grep:

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

this与thes 两个单词th与s是重复的,所以将“i”与“e”列于“()”符号当中,并以“|”分隔,即可查询"this"或者"thes"字符串

[root@localhost opt]# egrep -n 'th(i|e)s' httpd.conf 

等同于

[root@localhost opt]# grep -n 'th[ie]s' httpd.conf 

查询开头的"A"结尾是"C",中间有一个以上的"xyz"字符串

  • (只能匹配中间为xyz的,AxyzxyC则不能匹配)
[root@localhost opt]# egrep -n 'A(xyz)+C' httpd.conf 
364:AxyzC
366:AxyzxyzC

正则表达式总结

  • grep命令都可以使用egrep实现
    !!!特殊情况:
    grep ‘o\ {2\ }’ /etc/passwd # 特殊符号需要用脱意符号\,不然无法识别
    egrep ‘o{2}’ /etc/passwd # 用egrep命令,不需要脱意,{}表示前边字符的重复范围

  • grep命令

命令基本格式
grep -cinvABC 'word' filename
-c '行数'

-i '不区分大小写'

-n '显示行号'

-v '取反'

-r '遍历所有子目录'

-A '后面跟数字,过滤出符合要求的行以及下面n行'

-B '同上,过滤出符合要求的行以及上面n行'

-C '同上,同时过滤出符合要求的行以及上下各n行'

三、文本处理器

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

3.1 sed 工具

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

3.1.1 sed 的工作流程

主要包括读取、执行和显示三个过程。

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

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

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

在这里插入图片描述

  • sed 只是复制一份到缓存里进行修改,不会对原本的数据修改
  • 用sed -i 命令覆盖原有的硬盘中的文件(危险)
  • 第一件事就是备份

3.1.2 sed 命令常见用法

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

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

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

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

常见的sed命令选项

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

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

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

3.1.3 用法示例

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

输出所有内容,等同于 cat test.txt

[root@localhost opt]# sed -n 'p' test.txt 
1
2
3
4
5
6
7
8
9
10
aaa
bbb
ccc
'等同于cat命令'
[root@localhost opt]# cat test.txt 
1
2
3
4
5
6
7
8
9
10
aaa
bbb
ccc

输出第 3 行

[root@localhost opt]# sed -n '3p' test.txt 
3

输出 3~5 行

[root@localhost opt]# sed -n '3,5p' test.txt 
3
4
5

输出所有奇数行,n 表示读入下一行资料,先输出第一行,在到第二行的时候再读取下一行的内容再输出

[root@localhost opt]# sed -n 'p;n' test.txt 
1
3
5
7
9
aaa
ccc

输出所有偶数行,把n和p调换位置,先读取下一行,再进行输出

[root@localhost opt]# sed -n 'n;p' test.txt 
2
4
6
8
10
bbb
  • 这里说的奇数行和偶数行是相对的,不是绝对的,是相对指定的第一行
[root@localhost opt]# sed -n '1,10{p;n}' test.txt    '输出1-10行的奇数行'
1
3
5
7
9
[root@localhost opt]# sed -n '2,10{p;n}' test.txt      '输出2-10行的奇数行'
2
4
6
8
10
[root@localhost opt]# sed -n '2,10{n;p}' test.txt     '输出2-10行的偶数行'
3
5
7
9
aaa
  • 为什么会输出aaa(aaa是第11行)?
    命令加载是把整个文件的内容加载到缓存中,整个一行一行读取,执行完10后,n跳到下一行,自动跳到aaa,后面有p,就输出

输出第2行以后的行

[root@localhost opt]# sed -n '2,$p' test.txt 
2
3
4
5
6
7
8
9
10
aaa
bbb
ccc
  • sed 命令的基本用法,sed 命令结合正则表达式时,格式略有不同,正则表达式以“/”包围。

sed 命令与正则表达式结合使用:

输出包含the 的行
(相当于vi编辑器中的查找替换,使用到 / )

[root@localhost opt]# sed -n '/the/p' httpd.conf 
  • 1

输出从第4行到第一个包含the的行:

[root@localhost opt]# sed -n '4,/the/p' test.txt 
4
5
6
7
8
9
10
the

输出包含the 的行所在的行号,等号(=)用来输出行号

[root@localhost opt]# sed -n '/the/=' test.txt 
11
13

输出以root为开头的行

[root@localhost opt]# sed -n '/^root/p' /etc/passwd 
root:x:0:0:root:/root:/bin/bash
等同于:
[root@localhost opt]# grep  '^root' /etc/passwd 
root:x:0:0:root:/root:/bin/bash

输出以数字结尾的行

[root@localhost opt]# sed -n '/[0-9]$/p' httpd.conf 
#Listen 12.34.56.78:80
Listen 80
#ServerName www.example.com:80
AddDefaultCharset UTF-8

输出包含单词wood的行,/ / 做条件筛选,< >代表单词边界,最后用 ’ '

[root@localhost opt]# sed -n '/\<wood\>/p' httpd.conf 
this is wood

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

下面命令中 nl 命令用于计算文件的行数,结合该命令可以更加直观地查看到命令执行的结果。
这些操作只针对的是缓存区的文件,并没有对原文件进行操作。
匹配关键词的,一定要加查找符号//

nl 命令用于计算文件的行数(n相当于number,l相当于list)

[root@localhost opt]# nl test.txt 
     1	1
     2	2
     3	3
     4	4
     5	5
     6	6
     7	7
     8	8
     9	9
    10	10
    11	the
    12	aaa
    13	the aaa
    14	bbb
    15	ccc

删除第 3 行

[root@localhost opt]# nl test.txt | sed '3d'
     1	1
     2	2
     4	4
     5	5
     6	6
     7	7
     8	8
     9	9
    10	10
    11	the
    12	aaa
    13	the aaa
    14	bbb
    15	ccc

删除第4-6行

[root@localhost opt]# nl test.txt | sed '4,6d'
     1	1
     2	2
     3	3
     7	7
     8	8
     9	9
    10	10
    11	the
    12	aaa
    13	the aaa
    14	bbb
    15	ccc

删除包含有the的行

[root@localhost opt]# nl test.txt | sed '/the/d'
     1	1
     2	2
     3	3
     4	4
     5	5
     6	6
     7	7
     8	8
     9	9
    10	10
    12	aaa
    14	bbb
    15	ccc

删除不包含the的行,用 ! 符号表示取反操作

[root@localhost opt]# nl test.txt | sed '/the/!d'
    11	the
    13	the aaa

删除以小写字母开头的行

[root@localhost opt]# sed '/^[a-z]/d' test.txt 
1
2
3
4
5
6
7
8
9
10

删除以" . "结尾的行 ( . 作为普通符号,要加转义符)

[root@localhost opt]# sed '/\.$/d' test.txt

删除所有空行 (空行用^$ 表示)

[root@localhost opt]# sed '/^$/d' test.txt

注 意 : 若 是 删 除 重 复 的 空行 , 即 连 续 的 两个空 行 只 保 留 一 个(3个保留2个,4个保留2个,5个保留3个) ,
执 行“sed -e ‘/^ $ /{n;/^$/d}’ test.txt”命令即可实现。n 表示读下一行数据。

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

使用cat -s test.txt,最后只保留一行空行

[root@localhost opt]# cat -s test.txt

替换符合条件的文本(s、c、y)

s(字符串替换)
c(整行/整块替换)
y(字符转换)

将每行中的第一个the 替换为 THE

[root@localhost opt]# sed 's/the/THE/' test.txt 
1
2
3
4
5
6
7
8
9
10
THE the the
aaa
THE aaa
bbb
ccc

将每行中的第 2 个 the 替换为 THE

[root@localhost opt]# sed 's/the/THE/2' test.txt 
1
2
3
4
5
6
7
8
9
10
the THE the
aaa
the aaa
bbb
ccc

将文件中的所有the 替换为 THE (g代表global,全局替换)

[root@localhost opt]# sed 's/the/THE/g' test.txt 
1
2
3
4
5
6
7
8
9
10
THE THE THE
aaa
THE aaa
bbb
ccc

将文件中的所有 t 删除(替换为空串)

[root@localhost opt]# sed 's/t//g' test.txt 
1
2
3
4
5
6
7
8
9
10
he he he
aaa
he aaa
bbb
ccc

在每行行首插入#号

[root@localhost opt]# sed 's/^/#/' test.txt 
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#the the the
#aaa
#the aaa
#bbb
#ccc

把包含the的行前面全部加#注释掉

[root@localhost opt]# sed '/the/s/^/#/' test.txt 
1
2
3
4
5
6
7
8
9
10
#the the the
aaa
#the aaa
bbb
ccc

在每一行的末尾加入关键词EOF

[root@localhost opt]# sed 's/$/EOF/' test.txt 
1EOF
2EOF
3EOF
4EOF
5EOF
6EOF
7EOF
8EOF
9EOF
10EOF
the the theEOF
aaaEOF
the aaaEOF
bbbEOF
cccEOF

'前面可以空一格'
[root@localhost opt]# sed 's/$/ EOF/' test.txt    
1 EOF
2 EOF
3 EOF
4 EOF
5 EOF
6 EOF
7 EOF
8 EOF
9 EOF
10 EOF
the the the EOF
aaa EOF
the aaa EOF
bbb EOF
ccc EOF

13-16行中所有的the替换成THE

[root@localhost opt]# sed '13,16s/the/THE/g' test.txt 
1
2
3
4
5
6
7
8
9
10
the the the
the the the
THE THE THE
THE THE THE
THE THE THE
THE THE THE
the the the
the the the
the the the
aaa
the aaa
bbb
ccc

将包含the的所有行中的 abc 都替换成ABC

[root@localhost opt]# sed '/the/s/abc/ABC/g' test.txt 
1
2
3
4
5
6
7
8
9
10
the the the
the the the
the ABC the the
the the the
the ABC the the
the the the
the the the
the the the
the the the
aaa
the aaa
bbb
ccc

如果加了-i ,原文件就被修改了

[root@localhost opt]# sed -i '/the/s/abc/ABC/g' test.txt 
  • 1

迁移符合条件的文本

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

将包含有ABC的行,复制到剪切板,原有的行删掉,在文件末尾粘贴
(默认空一行)

[root@localhost opt]# sed '/ABC/{H;d};$G' test.txt
1
2
3
4
5
6
7
8
9
10
the the the
the the the
the the the
the the the
the the the
the the the
the the the
aaa
the aaa
bbb
ccc

the ABC the the
the ABC the the

把1-10行粘贴到第19行后面,原有的删除,
如果不加d,就相当于复制粘贴,原有的不变

[root@localhost opt]# sed '1,10{H;d};19G' test.txt 
the the the
the the the
the ABC the the
the the the
the ABC the the
the the the
the the the
the the the
the the the

1
2
3
4
5
6
7
8
9
10
aaa
the aaa
bbb
ccc

把包含有the的行保存到另外一个文件中abc.txt

[root@localhost opt]# sed '/the/w abcd.txt' test.txt
[root@localhost opt]# cat abcd.txt
the the the
the the the
the ABC the the
the the the
the ABC the the
the the the
the the the
the the the
the the the
the aaa

将文件/opt/abcd.txt 的内容(123)添加到test.txt文件包含 the 的每行以后

[root@localhost opt]# sed '/the/r /opt/abcd.txt' test.txt
1
2
3
4
5
6
7
8
9
10
the the the
123
the the the
123
the ABC the the
123
the the the
123
the ABC the the
123
the the the
123
the the the
123
the the the
123
the the the
123
aaa
the aaa
123
bbb
ccc

第3行后加一个NEW

[root@localhost opt]# sed '3aNEW' test.txt
1
2
3
NEW
4
5
6
7
8
9
10
the the the
the the the
the ABC the the
the the the
the ABC the the
the the the
the the the
the the the
the the the
aaa
the aaa
bbb
ccc

在包含the 的每行后插入一个新行,内容为 New

[root@localhost opt]# sed '/the/aNEW' test.txt 
1
2
3
4
5
6
7
8
9
10
the the the
NEW
the the the
NEW
the ABC the the
NEW
the the the
NEW
the ABC the the
NEW
the the the
NEW
the the the
NEW
the the the
NEW
the the the
NEW
aaa
the aaa
NEW
bbb
ccc

在指定的行后面插入指定的行:
在第3行后面加入两行NEW1和NEW2
\n表示转行符

[root@localhost opt]# sed '3aNEW1\nNEW2' test.txt 
1
2
3
NEW1
NEW2
4
5
6
7
8
9
10
the the the
the the the
the ABC the the
the the the
the ABC the the
the the the
the the the
the the the
the the the
aaa
the aaa
bbb
ccc

使用脚本编辑文件

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

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

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

首先把操作的 语句写到单独的文件中(分行写)

[root@localhost ~]# vi opt.list		'编辑指令放到/opt.list中'
1,5H
1,5d
17G
[root@localhost ~]# sed -f opt.list test.txt '使用opt.list文件指令编辑test.txt文件'

sed 直接操作文件示例

自动化修改配置文件:
(精确匹配)以Listen开头的行,s替换80为192.168.100.10/80,g全局

[root@localhost opt]# sed -i '/^Listen/s/80/192.168.100.10:80/g' httpd.conf 
[root@localhost opt]# vim httpd.conf 
Listen 192.168.100.10:80

在这里插入图片描述

[root@localhost opt]# sed -i '/^#ServerName/s/^#//g' httpd.conf | sed -i '/example/s/example/yyc/g' httpd.conf
[root@localhost opt]# vim httpd.conf 
  • 在这里插入图片描述

编写一个脚本,用来调整 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 '增加权限'

sed命令总结

sed工具除了调用文件或脚本执行命令,否则命令都需要加上’'符号

即:调用 sed 命令有两种格式

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

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

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

  • -n选项在符合条件输出和结合正则表达式的时候使用

  • {}用于奇数行和偶数行的筛选或者奇数行和偶数号的其他操作

  • sed 命令结合正则表达式时,格式略有不同,正则表达式以“/”包围

  • 使用sed删除命令时,nl 命令用于计算文件的行数,结合该命令可以更加直观地查看到命令执行的结果,而不使用-n

3.2 awk工具

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

3.2.1 awk常见用法

单引号加上大括号“{}”用于设置对数据进行的处理动作

awk 可以直接处理目标文件,也可以通过“-f”读取脚本对目标文件进行处理

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

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

查找出/etc/passwd 的用户名、用户 ID、组 ID 等列(位置变量,第1、3、4个字段以冒号分割出来)

  • $1,$3,$4之间用逗号隔开,输出的内容会有空格间隔
  • 若$1 $3 $4之间不用逗号隔开,则输出的内容不会有空格间隔,会连在一起
[root@localhost opt]# awk -F ':' '{print $1,$3,$4}' /etc/passwd
root 0 0
bin 1 1
daemon 2 2
adm 3 4
lp 4 7
......
  • awk 从输入文件或者标准输入中读入信息,与 sed 一样,信息的读入也是逐行读取的。

  • 不同的是 awk 将文本文件中的一行视为一个记录,而将一行中的某一部分(列)作为记录中的一个字段(域)

  • 为了操作这些不同的字段,awk 借用 shell 中类似于位置变量的方法, 用**$1、$2、$3„顺序地表示行(记录)中的不同字段**。另外 awk 用$0 表示整个行(记录)

  • 不同的字段之间是通过指定的字符分隔

  • awk 默认的分隔符是空格

  • awk 允许在命令行中用“-F 分隔符”的形式来指定分隔符

awk 命令对/etc/passwd 文件的处理过程图:
在这里插入图片描述
awk 包含几个特殊的内建变量(可直接用):

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

3.2.2 用法示例

按行输出文本

输出所有内容

awk '{print}' test.txt	   //输出所有内容,等同于 cat test.txt
awk '{print $0}' test.txt	 //输出所有内容,等同于 cat test.txt

输出第 1~3 行内容

[root@localhost opt]# awk 'NR==1,NR==3{print}' test.txt 
1
2
3
或者
[root@localhost opt]# awk '(NR>=1)&&(NR<=3){print}' test.txt 
1
2
3

输出第 1 行、第 3 行内容

[root@localhost opt]# awk 'NR==1||NR==3{print}' test.txt 
1
3

输出所有奇数行的内容

awk '(NR%2)==1{print}' test.txt

输出所有偶数行内容

awk '(NR%2)==0{print}' test.txt

输出以root开头的行 (两个斜杠/必须加,表示字段的筛选)

awk '/^root/{print}' /etc/passwd

输出以 nologin 结尾的行

awk '/nologin$/{print}' /etc/passwd

统计以/bin/bash 结尾的行数,等同于 grep -c “/bin/bash$” /etc/passwd

  • 先写’BEGIN{x=0}; ;END{print x}’ ,然后再写中间的匹配// 以/bin/bash结尾 ,因为/有其他匹配的意思,要加转义符号\ ,最后再加{x++},转到下一行
awk 'BEGIN {x=0} ; /\/bin\/bash$/{x++};END {print x}' /etc/passwd
8

等同于:
[root@localhost ~]# grep "bash$" /etc/passwd | wc -l
8
[root@localhost ~]# grep -c "bash$" /etc/passwd
8

统计以空行分隔的文本段落数(每一段都会以空行间隔)

[root@localhost opt]# awk 'BEGIN{RS=""};END{print NR}' test.txt 
2

按字段输出文本

输出每行中(以空格或制表位分隔)的第 3 个字段

awk '{print $3}' test.txt

输出每行中的第 1、3 个字段

awk '{print $1,$3}' test.txt

输出密码为空的用户的shadow 记录

awk -F: '$2=="!!"{print}' /etc/shadow

等同于:

awk 'BEGIN {FS=":"}; $2=="!!"{print}' /etc/shadow

输出以冒号分隔且第 7 个字段中包含/bash 的行的第 1 个字段(波浪号对应的是包含的意思

[root@localhost opt]# awk -F: '$7~"/bin/bash"{print $1}' /etc/passwd
root
yang
yc
yyc
yyyc
yyyyc
jack

输出第一个字段包含root,且有7个字段的第二个字段

[root@localhost opt]# awk -F: '($1~"root")&&(NF==7){print $2}' passwd
x

输出第七个字段不为/bin/bash且不为/sbin/nologin的行(必须要写全/bin/bash

[root@localhost opt]# awk -F: '($7!="/bin/bash")&&($7!="/sbin/nologin"){print}' 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

通过管道、双引号调用 Shell 命令

  • 操作命令放在{}中

  • 管道符号前面的命令输出的内容交给管道符号后面的命令处理

  • 结合正则表达式,正则表达式同样要被/包围

  • 调用的shell命令需要用""引起来

  • {}中多个命令之间也能过;分隔

调用wc -l 命令统计使用bash的用户个数(双引号之间直接调命令"wc -l")等同于 grep -c “bash$” /etc/passwd

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

调用w 命令,并用来统计在线用户数(前两行没有用,要n-2

[root@localhost opt]# w
 01:27:11 up  3:03,  1 user,  load average: 0.00, 0.01, 0.03
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/1    14.0.0.1         22:23    7.00s  0.12s  0.00s w

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

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

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

awk命令总结

sed操作指令置于’'中,awk比sed多一个{}

sed[选项] '操作' 参数
awk 选项 '模式或条件 {编辑指令}' 文件 1 文件 2

w,who,whoami,who am i

w 显示已经登录的用户及正在进行的操作
who 显示已经登录的用户名、终端名称、登录时间及登录IP
whoami 显示当前用户的用户名
who am i 显示登录系统的时候的用户名,即使已经切换到其他用户也显示登录时的用户
  • 一般输出关于段,列的信息使用awk,其他的使用sed或grep更加方便

  • awk输出的奇偶行都使用绝对路径
    sed输出的奇偶行都使用相对路径

  • 使用awk调用shell命令,统计数量时,n是个变量,可自定义
    若没有定义n的初始值,则n=0

  • awk判断条件中双引号之间的内容,如果有特殊符号不需要使用转义符

  • FS在{}中间使用,F在{}外面使用

3.3 sort 工具

  • 在 Linux 系统中,常用的文件排序工具有三种:sort、uniq、wc

  • sort 是一个以行为单位对文件内容进行排序的工具,也可以根据不同的数据类型来排序

sort 命令的语法

sort [选项] 参数

sort命令常用选项

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

sort命令示例

按照第一个字母排

[root@localhost opt]# sort 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:993:988::/var/lib/chrony:/sbin/nologin
colord:x:997:994:User for colord:/var/lib/colord:/sbin/nologin

将/etc/passwd 文件中第三列进行反向排序,根据第三列第一个字符的顺序排序(-t 字段分割,-r 反向排序,-k 指定第几个字段,)

[root@localhost opt]# sort -t ':' -rk 3 passwd 
nobody:x:99:99:Nobody:/:/sbin/nologin
......
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
sshd:x:74:74:Privilege-separated 
......
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
......
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin

将/etc/passwd 文件中第三列进行排序,并将输出内容保存至user.txt 文件中(-o 将排序后的结果转存至指定文件)

[root@localhost opt]# sort -t ':' -rk 3 passwd -o new01.txt

[root@localhost opt]# vim new01.txt 
nobody:x:99:99:Nobody:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
libstoragemgmt:x:998:995:daemon account for 
......

3.4 uniq工具

  • Uniq 工具在 Linux 系统中通常与 sort 命令结合使用,用于报告或者忽略文件中的重复行

  • 具体的命令语法格式为

uniq [选项] 参数
  • 1

uniq命令常用选项

选项 解释
-c 进行计数
-d 仅显示重复行
-u 仅显示出现一次的行

uniq命令示例

删除 test.txt 文件中的重复行(去不掉隔行相同的→先排序 sort test.txt | uniq 或者 sort -u test.txt

[root@localhost opt]# cat test.txt 
1
1
1
2
3
3
4
5
6
7
7

8
9
10
aaa
bbb
ccc
[root@localhost opt]# uniq test.txt 
1
2
3
4
5
6
7

8
9
10
aaa
bbb
ccc

删除 test.txt 文件中的重复行,并在行首显示该行重复出现的次数(单纯用uniq无法隔行删除,要先用sort进行排序

[root@localhost opt]# uniq -c test.txt 
      3 1
      1 2
      2 3
      1 2
      1 4
      1 5
      1 6
      2 7
      1 4
      1 
      1 8
      1 9
      1 10
      1 aaa
      1 bbb
      1 ccc
[root@localhost opt]# sort test.txt | uniq -c
      1      '这个第一行是空行'
      3 1
      1 10
      2 2
      2 3
      2 4
      1 5
      1 6
      2 7
      1 8
      1 9
      1 aaa
      1 bbb
      1 ccc

查找 test.txt 文件中的重复行(只显示重复行)

[root@localhost opt]# sort test.txt | uniq -d
1
2
3
4
7

4.5 tr 工具

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

命令语法格式:

tr [选项] [参数]
  • 1

tr 命令常用选项

选项 解释
-c 取代所有不属于第一字符集的字符
-d 删除所有属于第一字符集的字符
-s 把连续重复的字符以单独一个字符表示,去重
-t 先删除第一字符集较第二字符集多出的字符

tr 命令示例

将输入字符由大写转换为小写

[root@localhost opt]# echo "YYC" | tr 'A-Z' 'a-z'
yyc

压缩输入中重复的字符(对abc去重)

[root@localhost opt]# echo "aaabbbc" | tr -s 'abc'
abc

删除字符串中某些字符

[root@localhost opt]# echo 'abc' | tr -d 'ab'

猜你喜欢

转载自blog.csdn.net/yujia_666/article/details/108896872