gpt4 book ai didi

regex - 如何使用捕获的组来转换这些行?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:33 26 4
gpt4 key购买 nike

我正在尝试使用 sed 转换文件中的一堆文本行,如下所示:

{ Interop.SecurityStatus.AlgorithmMismatch, SecurityStatusPalErrorCode.AlgorithmMismatch },
{ Interop.SecurityStatus.BadBinding, SecurityStatusPalErrorCode.BadBinding },
{ Interop.SecurityStatus.BufferNotEnough, SecurityStatusPalErrorCode.BufferNotEnough },
{ Interop.SecurityStatus.CannotInstall, SecurityStatusPalErrorCode.CannotInstall },

为此:

[Interop.SecurityStatus.AlgorithmMismatch] = SecurityStatusPalErrorCode.AlgorithmMismatch,
[Interop.SecurityStatus.BadBinding] = SecurityStatusPalErrorCode.BadBinding,
[Interop.SecurityStatus.BufferNotEnough] = SecurityStatusPalErrorCode.BufferNotEnough,
[Interop.SecurityStatus.CannotInstall] = SecurityStatusPalErrorCode.CannotInstall,

到目前为止,这是我尝试使用我生疏的正则表达式知识来完成的:

$ sed -i 's/{ (.*), (.*) }/\[\1\] = \2/g' file_name

不幸的是,它似乎没有工作,因为我从我的终端返回了这个错误:

sed: -e expression #1, char 30: invalid reference \2 on `s' command's RHS

我不确定为什么会这样,因为据我所知我有 2 个括号(因此有 2 个捕获组)。有人可以向我解释为什么 sed 返回此错误,以及如何修复它吗?谢谢。

最佳答案

默认情况下,根据 POSIX spec , sed 使用基本 正则表达式 (BREs),其中 ()普通字符,因此必须用\引号作为元字符,以便按照您的意愿创建捕获组(但是请注意,{} 被视为您想要的普通字符):

sed -i 's/{ \(.*\), \(.*\) }/\[\1\] = \2/g' file_name

但是,鉴于您已经在使用非标准选项-i,您还可以通过激活对扩展的支持来让您的生活更轻松 具有 GNU sed 的非标准 -r 选项 的正则表达式 (ERE);虽然在这种特殊情况下使用 ERE 不会给您带来太多好处,但它们的功能通常会更像您期望的那样(从其他语言中得知):

sed -i -r 's/\{ (.*), (.*) \}/\[\1\] = \2/g' file_name

() 现在按照您预期的方式运行,但请注意现在是 {}需要被 \ 引用才能被视为文字,因为在 ERE 的上下文中,它们是量词中使用的元字符(例如 {1, 2}).

关于regex - 如何使用捕获的组来转换这些行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com