簡體   English   中英

正則表達式 select 幾行直到兩個連續的新行在 Mac 上不起作用

[英]Regex select several lines until two consecutive new lines is not working on Mac

我需要在以“Query #”開頭的行和兩個連續的回車符之間提取幾行文本(沿 500 MB 文檔的長度不同)。 這是在 Mac 上完成的。 例如,文檔格式為:

Query #1: 020.1-Bni_its1_2019_envio1set1

lines I need to extract


Alignments (the following lines I don't need)

xyz
xyx

Query #2: This and the following lines I need. And so on.

“對齊”一詞之前總是正好有兩個回車符。 所以基本上我需要 Query #.: 中的所有行,直到 Alignments。

我嘗試了以下正則表達式,但我只恢復了第一行。

ggrep -P 'Query #.*?(?:[\r\n]{2}|\Z)'

我已經在 Regex101多次迭代測試了正則表達式,但我還沒有找到答案。

預期的 output 為:

Query #1.   Text.

Lines I need to extract

Query #2: This and following lines I need.

Lines I need.

Query #....

使用pcregrep ,您可以使用

pcregrep -oM 'Query #.*(?:\R(?!\R{2}).*)*' file.txt > results.txt

這里,

  • o - 輸出匹配的文本
  • M - 啟用跨行匹配(將行尾放入“模式空間”)
  • Query #.*(?:\R(?.\R{2}).*)*匹配
    • Query # - 文字文本
    • .* - 線的rest
    • (?:\R(?.\R{2}).*)* - 零個或多個換行序列 ( \R ) 不緊跟兩個換行序列 ( (?!\R{2}) ) 然后是 rest 的行。

測試截圖:

在此處輸入圖像描述

正則表達式:現在你有兩個問題

有些人在遇到問題時會想“我知道,我會使用正則表達式”。 現在他們有兩個問題。

在每個 Unix 盒上的任何 shell 中使用任何AWK實現:

awk '/^Query #/{f=1} /^Alignments/{f=0} f' file

Output:

Query #1: 020.1-Bni_its1_2019_envio1set1

lines I need to extract


Query #2: This and the following lines I need. And so on.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM