目录
考虑如下测试配置文件 confile.txt
Sys=1
ManageState=ON
Configuration=1
TcpGroup=1
cpuThreshold=70
bwThreshold=80
TcpChannel=1
localPort=1110
remoteIp=10.0.6.1
remotePort=1111
TcpChannel=2
localPort=2221
remoteIp=10.0.6.2
remotePort=2222
TcpChannel=3
localPort=3332
remoteIp=10.0.6.3
remotePort=3333
TcpChannel=4
localPort=4443
remoteIp=10.0.6.4
remotePort=4444
TcpChannel=5
localPort=5554
remoteIp=10.0.6.5
remotePort=5555
LogLevel=ALL
1.grep查找关键字所在行号、查找关键字前后行
查找含有关键字的行,带 -n显示行号
[root@xxx ts]# grep 'TcpChannel' confile.txt
TcpChannel=1
TcpChannel=2
TcpChannel=3
TcpChannel=4
TcpChannel=5
[root@xxx ts]#
[root@xxx ts]# grep -n 'TcpChannel' confile.txt
7: TcpChannel=1
11: TcpChannel=2
15: TcpChannel=3
19: TcpChannel=4
23: TcpChannel=5
[root@xxx ts]#
查找TcpChannel及其后一行 -A1
[root@xxx ts]# grep -A1 'TcpChannel' confile.txt
TcpChannel=1
localPort=1110
--
TcpChannel=2
localPort=2221
--
TcpChannel=3
localPort=3332
--
TcpChannel=4
localPort=4443
--
TcpChannel=5
localPort=5554
[root@xxx ts]#
查找remotePort及其前一行 -B1
[root@xxx ts]# grep -B1 'remotePort' confile.txt
remoteIp=10.0.6.1
remotePort=1111
--
remoteIp=10.0.6.2
remotePort=2222
--
remoteIp=10.0.6.3
remotePort=3333
--
remoteIp=10.0.6.4
remotePort=4444
--
remoteIp=10.0.6.5
remotePort=5555
[root@xxx ts]#
2.sed删除指定行及其前后若干行
删除Channel 2的相关信息 --> 删除Channel2及其后3行(-i写入文件)
sed '/TcpChannel=2/,+3d' confile.txt
[root@xxx ts]# sed '/TcpChannel=2/,+3d' confile.txt
Sys=1
ManageState=ON
Configuration=1
TcpGroup=1
cpuThreshold=70
bwThreshold=80
TcpChannel=1
localPort=1110
remoteIp=10.0.6.1
remotePort=1111
TcpChannel=3
localPort=3332
remoteIp=10.0.6.3
remotePort=3333
TcpChannel=4
localPort=4443
remoteIp=10.0.6.4
remotePort=4444
TcpChannel=5
localPort=5554
remoteIp=10.0.6.5
remotePort=5555
LogLevel=ALL
[root@xxx ts]#
3.sed在匹配行前或后添加一行,并且保留空格
新增Channel 6 --> 例如在LogLevel行前依次插入数据
[root@xxx ts]# sed -i "/LogLevel/i\ TcpChannel=6" confile.txt
[root@xxx ts]# sed -i "/LogLevel/i\ localPort=6665" confile.txt
[root@xxx ts]# sed -i "/LogLevel/i\ remoteIp=10.0.6.6" confile.txt
[root@xxx ts]# sed -i "/LogLevel/i\ remotePort=6666" confile.txt
[root@xxx ts]#
[root@xxx ts]#
[root@xxx ts]# cat confile.txt
Sys=1
ManageState=ON
Configuration=1
TcpGroup=1
cpuThreshold=70
bwThreshold=80
TcpChannel=1
localPort=1110
remoteIp=10.0.6.1
remotePort=1111
TcpChannel=2
localPort=2221
remoteIp=10.0.6.2
remotePort=2222
TcpChannel=3
localPort=3332
remoteIp=10.0.6.3
remotePort=3333
TcpChannel=4
localPort=4443
remoteIp=10.0.6.4
remotePort=4444
TcpChannel=5
localPort=5554
remoteIp=10.0.6.5
remotePort=5555
TcpChannel=6
localPort=6665
remoteIp=10.0.6.6
remotePort=6666
LogLevel=ALL
[root@xxx ts]#
说明:
sed -i "/要匹配的/i\ 新的内容 " filename
sed -i "/要匹配的/a\ 新的内容 " filename
-i: 是在文件内部操作
第一个/和第二个/:固定写法
双引号内部的i:在前面插入 ;双引号内部的a:在匹配行后面添加
反斜杠\ 后的内容都作为输出,包括空格
参考资料:sed在匹配行前或后添加一行,并且保留空格 https://blog.csdn.net/qq_39677803/article/details/122626572