删除匹配模式后的“n”行很容易使用类似的东西:
IFM_MOUNT="/opt/insiteone/fuse-mount2/ifm"
sed -i "\|$IFM_MOUNT|,+6 d" smb.conf (deletes lines matching and next 6 lines)
但我的问题是,我也想删除匹配模式之前的 2 行。
如何实现? 我将调用该命令的文件是一个 Samba 配置文件,如下所示:
[DCCAArchive1]
comment = DCCA Archive File System
path = /opt/insiteone/fuse-mount1/ifm
read only = No
public = yes
case sensitive = yes
writable = yes
create mask=0777
guest ok = Yes
[DCCAArchive2]
comment = DCCA Archive File System
path = /opt/insiteone/fuse-mount2/ifm
read only = No
public = yes
case sensitive = yes
writable = yes
create mask=0777
guest ok = Yes
[DCCAArchive3]
comment = DCCA Archive File System
path = /opt/insiteone/fuse-mount3/ifm
read only = No
public = yes
case sensitive = yes
writable = yes
create mask=0777
guest ok = Yes
最佳答案
正如我评论的那样,如果格式是固定的(数据 block 之间的空行),这一行就可以完成工作:
awk -v RS="" '!/PATTERN/' input
如果不是这种情况,你可以试试这个 awk one-liner:
awk '{a[NR]=$0}/PATTERN/{for(i=NR-2;i<=NR+6;i++)d[i]=1}
END{for(i=1;i<=NR;i++)if(!d[i])print a[i]}' input
一个测试
- 使用
ifm
作为简化的PATTERN
- “数据 block ”之间没有空行
遵循您的规则:删除行
hit-2 -> hit+6
kent$ cat f fooooooooo [DCCAArchive1] comment = DCCA Archive File System path = /opt/insiteone/fuse-mount1/ifm read only = No public = yes case sensitive = yes writable = yes create mask=0777 guest ok = Yes barrrrrrrrrrrr [DCCAArchive2] comment = DCCA Archive File System path = /opt/insiteone/fuse-mount2/ifm read only = No public = yes case sensitive = yes writable = yes create mask=0777 guest ok = Yes kent$ awk '{a[NR]=$0}/ifm/{for(i=NR-2;i<=NR+6;i++)d[i]=1}END{for(i=1;i<=NR;i++)if(!d[i])print a[i]} ' f fooooooooo barrrrrrrrrrrr
编辑
使用来自 shell 变量的模式:
kent$ PAT="/fuse-mount2/ifm"
kent$ awk -v p="$PAT" '{a[NR]=$0}{if(match($0,p)>0){for(i=NR-2;i<=NR+6;i++)d[i]=1}}END{for(i=1;i<=NR;i++)if(!d[i])print a[i]} ' f
fooooooooo
[DCCAArchive1]
comment = DCCA Archive File System
path = /opt/insiteone/fuse-mount1/ifm
read only = No
public = yes
case sensitive = yes
writable = yes
create mask=0777
guest ok = Yes
barrrrrrrrrrrr
关于linux - sed - 删除匹配模式前后的 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29296965/