小智 9
基本上你是在模仿尾巴。在这个例子中 X = 20。以下示例将删除除最后 20 行之外的所有行:
sed -i -e :a -e '$q;N;21,$D;ba' filename
Run Code Online (Sandbox Code Playgroud)
解释:
sed当涉及到这样的任务时是相当复杂的。tail,grep或者awk会使这更容易,应该使用它。话虽如此,这是可能的。
以下解决方案改编自sed 和 Multi-Line Search and Replace。
sed -ni '
# if the first line copy the pattern to the hold buffer
1h
# if not the first line then append the pattern to the hold buffer
1!H
# if the last line then ...
${
# copy from the hold to the pattern buffer
g
# delete current line if it is followed by at least X more lines
# replace X-1 with the proper value
s/.*\n\(\(.*\n\)\{X-1\}\)/\1/
# print
p
}
' filename
Run Code Online (Sandbox Code Playgroud)
没有评论,它是一个漂亮的单线。如果你想消除,例如,除最后十行之外的所有内容,请使用:
sed -ni '1h;1!H;${;g;s/.*\n\(\(.*\n\)\{9\}\)/\1/;p;}' filename
Run Code Online (Sandbox Code Playgroud)