簡體   English   中英

如何使用 sed 在兩個模式之間插入“][”?

[英]How do I insert '][' in between the two patterns with sed?

我編寫了一個 Bash 腳本,它利用正則表達式來處理我用 Markdown 編寫的文本文件,以便它們可以准備好編譯為 .html 文件。 此處理的一項任務旨在更改如下所示的懶惰書寫的文本:

Verkle 樹正在成為以太坊即將進行的擴展升級的重要組成部分。 它們具有與 Merkle 樹相同的功能:[您可以將大量數據放入 Verkle 樹 3],並對任何單個或一組數據進行簡短的證明(“見證”),這些數據可以由只有樹根的人驗證。

編譯后將顯示鏈接的文本:

Verkle 樹正在成為以太坊即將進行的擴展升級的重要組成部分。 它們具有與 Merkle 樹相同的功能:[您可以將大量數據放入 Verkle 樹][3],並對這些數據的任何單個或一組數據進行簡短的證明(“見證”)這可以由只有樹根的人來驗證。

換句話說,我想替換[text that begins with a letter and consists of words, letters and punctuation. The text ends with a positive integer smaller than 100 int] [text that begins with a letter and consists of words, letters and punctuation. The text ends with a positive integer smaller than 100 int]其中[text that begins with a letter and consists of words, letters and punctuation.The text ends with a bracket][int]

以下是用於執行我上面描述的任務的代碼:

sed -i -E 's/(\[[a-zA-Z]{2,2}[\s\S]{1,100})(\[0-9]{1,2}\])/\1\][\2/g' file.txt; 

該代碼旨在讓我免於編寫額外的 '][' 並將自動為我完成。 該代碼不起作用,我不知道為什么。

您編寫的正則表達式符合 PCRE ,但您需要一個POSIX,因為sed僅支持 POSIX BRE 或 ERE。

您可以使用

sed -i -E 's/(\[[[:alpha:]]{2}([^][]*[^0-9])?)([0-9]{1,2}])/\1][\3/g' file

請參閱在線演示

s='Verkle trees are shaping up to be an important part of Ethereum'"'"'s upcoming scaling upgrades. They serve the same function as Merkle trees: [you can put a large amount of data into a Verkle tree3], and make a short proof ("witness") of any single piece, or set of pieces, of that data that can be verified by someone who only has the root of the tree.'
sed -E 's/(\[[[:alpha:]]{2}([^][]*[^0-9])?)([0-9]{1,2}])/\1][\3/g' <<< "$s"

輸出:

Verkle trees are shaping up to be an important part of Ethereum's upcoming scaling upgrades. They serve the same function as Merkle trees: [you can put a large amount of data into a Verkle tree][3], and make a short proof ("witness") of any single piece, or set of pieces, of that data that can be verified by someone who only has the root of the tree.

詳情

  • (\\[[[:alpha:]]{2}([^][]*[^0-9])?) - 第 1 組 ( \\1 ):
    • \\[ - 一個[字符
    • [[:alpha:]]{2} - 兩個字母
    • ([^][]*[^0-9])? - 除了[]之外的零個或多個字符的可選序列,然后是非數字字符
  • ([0-9]{1,2}]) - 第 3 組 ( \\3 ):一位或兩位數字。

替換為\\1][\\3 ,第 1 組 + ][ + 第 3 組值串聯(第 2 組未使用,因為它僅用於匹配第 1 組內的可選部分,並且sed 、POSIX、正則表達式風格不支持非捕獲組)。

暫無
暫無

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

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