问题描述
sed -e '/XXXX/,+4d' fv.out
我必须找到一个文件中的特定模式,删除5行以上和4号线下方同时进行。我发现上面的行删除包含其下面的模式,四大行就行了。
I have to find a particular pattern in a file and delete 5 lines above and 4 lines below it simultaneously. I found out that the line above removes the line containing the pattern and four lines below it.
sed -e '/XXXX/,~5d' fv.out
在SED手册它被赋予了〜重新presents随后是图案的线条。但是,当我试了一下,以下是被删除的图案线条。
In sed manual it was given that ~ represents the lines which is followed by the pattern. But when i tried it, it was the lines following the pattern that was deleted.
那么,如何删除上述5线和4线的线下同时包含模式?
So, how do I delete 5 lines above and 4 lines below a line containing the pattern simultaneously?
推荐答案
使用的一种方法 SED
,假设模式不够接近对方:
One way using sed
, assuming that the patterns are not close enough each other:
内容 script.sed
:
## If line doesn't match the pattern...
/pattern/ ! {
## Append line to 'hold space'.
H
## Copy content of 'hold space' to 'pattern space' to work with it.
g
## If there are more than 5 lines saved, print and remove the first
## one. It's like a FIFO.
/\(\n[^\n]*\)\{6\}/ {
## Delete the first '\n' automatically added by previous 'H' command.
s/^\n//
## Print until first '\n'.
P
## Delete data printed just before.
s/[^\n]*//
## Save updated content to 'hold space'.
h
}
### Added to fix an error pointed out by potong in comments.
### =======================================================
## If last line, print lines left in 'hold space'.
$ {
x
s/^\n//
p
}
### =======================================================
## Read next line.
b
}
## If line matches the pattern...
/pattern/ {
## Remove all content of 'hold space'. It has the five previous
## lines, which won't be printed.
x
s/^.*$//
x
## Read next four lines and append them to 'pattern space'.
N ; N ; N ; N
## Delete all.
s/^.*$//
}
样运行:
sed -nf script.sed infile
这篇关于删除N1 previous线和n2线相对于含有的图案的线以下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!