文本处理三剑客

发布时间 2023-11-06 23:03:09作者: q_7

一:grep命令

grep用于查找符合条件和满足的正则表达式

语法格式:

grep 选项 匹配的条件 文本文件  

常用的选项

-n 对于匹配的内容显示行号
-v 反向选择(不要匹配到的内容)
-r 递归查找子目录中的文件中(符合条件的内容显示出来)
-c 只打印匹配的行数(符合条件的行数)
-i 忽略大小写
-l 只打印匹配的文件名(只打印出包含匹配的字符的文件名)
#搜索这个目录下包含11的文件名
[root@localhost opt]# grep -r -l 11 /opt/
/opt/qq.txt
/opt/ww.txt
[root@localhost opt]# 

#搜索不包含11的内容的行
[root@localhost opt]# cat qq.txt 
11
22
33
44

[root@localhost opt]# grep -v 11 /opt/qq.txt 
22
33
44

[root@localhost opt]# 

#搜索11所对应的行
[root@localhost opt]# grep -n 11 /opt/qq.txt 
1:11
[root@localhost opt]# 

 

  

二:sed命令

 

 

 

三:awk命令

逐行读取文本,默认以空格或tab键为分隔符进行分隔,将分隔所得的各个字段保存到内建变量中,并按模式或者条件执行编辑命令。

格式:

awk [选项参数] 'script' var=value file(s)
或
awk [选项参数] -f scriptfile var=value file(s)

选项

-F 以什么作为分割,然后前面是$1,后面是$2
   
   
   
   

 

 

 

常见的列子:

1)打印一行的哪个数 {print$1}

[root@localhost opt]# free -th
              total        used        free      shared  buff/cache   available
Mem:           1.9G        664M        808M         10M        511M        1.1G
Swap:          4.0G          0B        4.0G
Total:         5.9G        664M        4.8G
[root@localhost opt]# free -th | grep Total | awk '{print$1}'
Total:
[root@localhost opt]# 

2)打印一行的所有内容

[root@localhost opt]# free -th | grep Total | awk '{print$0}'
Total:         5.9G        666M        4.8G
[root@localhost opt]# 

3)以a为分割,打印$1

[root@localhost opt]# cat 11.txt 
sdfsdfgasdgafgdf
[root@localhost opt]# awk -F 'a' '{print$1}' 11.txt 
sdfsdfg
[root@localhost opt]# 


#打印$2
[root@localhost opt]# awk -F 'a' '{print$2}' 11.txt 
sdg
[root@localhost opt]# 

#打印$3
[root@localhost opt]# awk -F 'a' '{print$3}' 11.txt 
fgdf
[root@localhost opt]#