如何删除shell中匹配的行和前两行



我有一个如下的文件。

first line
second line
third line
fourth line
fifth line

如何使用shell命令删除匹配的行和前面的2行?例如,我想匹配第四行并删除第四行、第三行和第二行。我得到了我可以使用sed -i '/second/q' filename删除匹配行之后的行,但如何实现删除珍贵行?

请您尝试以下内容,用GNUawk中显示的示例编写和测试。使用要在该特定行中匹配的字符串更改$0=="fourth line"

tac Input_file | 
awk -v line="4" -v skipLines="2" -v totLines=$(wc -l < Input_file) '
FNR==(totLines-line+1) && $0=="fourth line"{
++count
next
}
count && count++<=skipLines{ next }
1
' | tac

解释:添加以上详细解释。

tac Input_file |                     ##Using tac command to print contents from bottom to top.
awk -v line="4" -v skipLines="2" -v totLines=$(wc -l < Input_file) '
##passed tac output to awk program which has 3 variables in it.
##line is on which line you want to match for pattern, skipLines(how many lines you want to skip), totLines has total lines in Input_file
FNR==(totLines-line+1) && $0=="fourth line"{
##Checking if current line is which we are looking for and its same as needed pattern.
++count                            ##Increasing count with 1 here.
next                               ##next will skip all statements from here.
}
count && count++<=skipLines{ next }  ##Checking if count is NOT NULL and count is <= skipLines, when both are TRUE do next to skip lines.
1                                    ##1 will print the current line.
' | tac                              ##Sending awk output to tac to get it in its actual order.

注意:请确保只要有Input_file,就可以将实际文件名放在那里。

仅awk版本:

$ awk -v p=3
{
b[FNR%(p+1)]=$0                 # p+1 sized modulo implemented circular buffer b
if(((FNR+1)%(p+1)) in b)        # print the one to be overwritten next
print b[(FNR+1)%(p+1)]      # ... if it exist
}
/fourth line/ {                     # when match met
delete b                        # reset time for b
}
END {                               # in the end
for(i=1;i<=(p+1);i++)           # we flush all the values left in buffer
if(((FNR+i)%(p+1)) in b)
print b[(FNR+i)%(p+1)]
}

输出:

first line
fifth line

最新更新