简体   繁体   中英

grep first occurance of a string n lines prior, once matched with another string

I need to find first occurance of "A" that comes n lines prior, after matching of another string "B".

Say

A(capture since nearest to next B)
..
..
B
..
..
A (Dont capture)
A (capture, nearest to next B)
..
..
B
task: capture "A"s which occur prior to "B".
Cant use grep -r -B 5 (or 6 or 7 since it could be any lines prior) "B" | grep "A"
since "A" could be any number of lines prior, and I need first occurance of such prior "A".
Basically find "A" of each "B".
Any solution?

If not grep, what would be the script to this?

Using awk , you may do this:

awk '/^A/ {f=$0} /^B/ {print f}' file
A(capture since nearest to next B)
A (capture, nearest to next B)

It stores the line in variable f when line starts with A
Later when it finds B

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM