如何使用 sed 在两个模式之间插入 ']['?

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

我写了一个 Bash 脚本,它按顺序使用正则表达式 处理我用 markdown 编写的文本文件,以便它们可以准备好编译为 .html 文件。此处理的一项任务是 更改看起来像这样的懒惰编写的文本:

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.

转换为编译后会显示 link:

的文本

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.

换句话说,我想用[text that begins with a letter and consists of words, letters and punctuation.The text ends with a bracket][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]

以下是用于执行上述任务的代码片段:

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

该代码旨在让我免于编写额外的“][”,并且会自动为我完成。代码不起作用,我不知道为什么。

您写的正则表达式是 PCRE-compliant, but you need a POSIX 一个,因为 sed 只支持 POSIX BRE 或 ERE。

你可以使用

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

online demo:

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}])/][/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 组 (</code>): <ul> <li><code>\[ - 一个 [ 字符
  • [[:alpha:]]{2} - 两个字母
  • ([^][]*[^0-9])? - [] 以外的零个或多个字符的可选序列,然后是非数字字符
  • ([0-9]{1,2}]) - 第 3 组 (</code>):一个或两个数字。</li> </ul> <p>替换为 <code>][,组 1 + ][ + 组 3 值连接(不使用组 2,因为它仅用于匹配组 1 中的可选部分,并且 sed, POSIX, regex flavor 不支持非捕获组)。