I have a grep command returns more than 20 lines. I need to display the 4th line from last line of the grep result,
lets say my file has below data,
test.txt
one
two
three
four
five
six
seven
eight
nine
ten
Task is :
grep "nine" test.txt // i want seven as result
Can someone please help me with this ?
You can use -B
option in grep
to take any number of lines before your search line and then head -1
will get you the first line from output:
grep -B2 nine file | head -1
seven
Given:
$ cat file
one
two
three
four
five
six
seven
eight
nine
ten
You can use awk
to keep n+1
number of lines in a buffer and then print the line that is n
lines before the match:
$ awk -v n=2 'BEGIN{b=n+1} { buf[NR%b]=$0 } /nine/{ print buf[(NR-n)%b] }' file
seven
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;
.
If you want the nth line from the end, then clearly your input is limited so you don't need a streaming solution. So you might as well reverse the input and print the nth line from the beginning:
grep ... | tac | sed -n "${n}{p; q; }"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.