使用 GNU sed (macOS) 4.4 将一个捕获组替换为另一个 [英] Replace one capture group with another with GNU sed (macOS) 4.4

查看:54
本文介绍了使用 GNU sed (macOS) 4.4 将一个捕获组替换为另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾了其他一些外围问题,但没有找到解决我的问题的方法,所以如果这与我错过的问题重复,我很抱歉.

I've looked around some other peripheral questions and haven't been able to find a solution to my problem, so I'm sorry if this is a duplicate to something I missed.

基本上,我有以下 GNU sed 命令:

Basically, I have the following GNU sed command:

sed -E -imr 's/^(\w)+/(\w)+$/g' file

应该用该行的最后一个单词替换一行的第一个单词.

which is supposed to replace the first word of a line with the last word of the line.

第一个正则表达式 ^(\w)+ 效果很好并且匹配每一行的第一个单词.问题是该命令将第一个单词替换为文字字符串 (w)+$

The first regex ^(\w)+ works great and matches the first word of each line. The problem is that the command replaces that first word with the literal string (w)+$

我试图转义反斜杠、括号、运算符,但我没有运气使正则表达式在命令的输出部分工作.

I've tried to escape the backslash, the parentheses, the operators, but I've had no luck in making the regex work in the output part of the command.

可以使用正则表达式捕获组替换不同的正则表达式捕获组吗?需要转义什么,或者需要使用什么替代语法?

Can one use a regex capture group to replace a different regex capture group? What needs to be escaped, or what alternative syntax needs to be used?

我在 macOS 上通过 brew 安装的 coreutils 使用 GNU sed,所以这个问题的答案可能不适用于其他版本的 sed,如 macOS 上的本机 BSD.

I'm using GNU sed on macOS from brew installed coreutils, so the answers to this question might not work across other versions of sed like native BSD on macOS.

推荐答案

替换不包含正则表达式,它包含一个可以引用正则表达式中定义的捕获组的字符串.要将第一个单词替换为最后一个单词,您需要捕获最后一个单词和该行的其余部分:

The replacement doesn't contain a regex, it contains a string which could reference capture groups defined in the regex. To replace the first word by the last one, you need to capture the last word and the rest of the line:

sed -r 's/^\w+(.*\b)(\w+)$/\2\1/'  
            |    |    |
         Matches |    |
         the 1st |    Matches the last word
         word    |
                Matches everything in the middle
                up to a "word boundary"

请注意,-r\w\b 可能不适用于所有 sed 版本,但它们应该可以在最近的 GNU sed 中工作.

Note that -r, \w, and \b might not work in all sed versions, but they should work in recent GNU sed.

这篇关于使用 GNU sed (macOS) 4.4 将一个捕获组替换为另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆