最后一行的grep命令

时间:2017-04-24 16:55:44

标签: linux shell unix

我有一个grep命令返回超过20行。我需要显示grep结果最后一行的第4行,

假设我的文件包含以下数据,

test.txt

one  
two  
three  
four  
five  
six  
seven  
eight  
nine  
ten  

任务是:

grep "nine" test.txt // i want seven as result 

有人可以帮帮我吗?

4 个答案:

答案 0 :(得分:4)

您可以使用-B中的grep选项在搜索行之前获取任意数量的行,然后head -1将从输出中获取第一行:

grep -B2 nine file | head -1

seven

答案 1 :(得分:0)

假设:

$ cat file
one  
two  
three  
four  
five  
six  
seven  
eight  
nine  
ten  

您可以使用awk在缓冲区中保留n+1行数,然后在匹配前打印n行的行:

$ awk -v n=2 'BEGIN{b=n+1} { buf[NR%b]=$0 } /nine/{ print buf[(NR-n)%b] }' file 
seven  

答案 2 :(得分:0)

In awk:

$ awk -v s=nine '$0~s{print q}{q=p;p=$0}' file
seven  

Explained:

awk -v s='nine' '   # search string into s var
$0~s { print q }    # if match, print buffer q
{ q=p; p=$0 }       # q is previous of previous
' file

If there's going to be only one match you can add exit after the print q;.

答案 3 :(得分:0)

如果你想从最后一行开始,那么显然你的输入是有限的,所以你不需要流媒体解决方案。所以你也可以反转输入并从头开始打印第n行:

grep ... | tac | sed -n "${n}{p; q; }"