首页 > 解决方案 > 如何使用 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 bracket][int]

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

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

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

标签: regexsedmarkdownregex-group

解决方案


您编写的正则表达式与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])?- 一个可选的零个或多个字符序列,除了[and]然后是一个非数字字符
  • ([0-9]{1,2}])- 第 3 组 ( \3):一位或两位数。

替换为\1][\3, Group 1 + ][+ Group 3 值连接(不使用 Group 2,因为它仅用于匹配 Group 1 内的可选部分,并且sedPOSIX 正则表达式不支持非捕获组)。


推荐阅读