简体   繁体   English

grep 字符串在 n 行之前第一次出现,一旦与另一个字符串匹配

[英]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".在匹配另一个字符串“B”之后,我需要找到第 n 行之前出现的“A”。

Say

A(capture since nearest to next B) A(从最接近下一个 B 开始捕获)
.. ..
.. ..
B
.. ..
.. ..
A (Dont capture) A(不要捕捉)
A (capture, nearest to next B) A(捕获,最靠近下一个 B)
.. ..
.. ..
B
task: capture "A"s which occur prior to "B".任务:捕获出现在“B”之前的“A”。
Cant use grep -r -B 5 (or 6 or 7 since it could be any lines prior) "B" |不能使用 grep -r -B 5(或 6 或 7,因为它可能是之前的任何行)"B" | grep "A"搜索“A”
since "A" could be any number of lines prior, and I need first occurance of such prior "A".因为“A”可以是任意数量的行,我需要首先出现这样的“A”。
Basically find "A" of each "B".基本上找到每个“B”的“A”。
Any solution?有什么解决办法吗?

If not grep, what would be the script to this?如果不是grep,那么这个脚本是什么?

Using awk , you may do this:使用awk ,您可以这样做:

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当行以A开头时,它将行存储在变量f
Later when it finds B后来当它找到B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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