简体   繁体   English

如何使用 sed 替换正则表达式捕获组?

[英]How to use sed to replace regex capture group?

I have a large file with many scattered file paths that look like我有一个大文件,其中包含许多分散的文件路径,看起来像

lolsed_bulsh.png

I want to prepend these file names with an extended path like:我想在这些文件名前面加上一个扩展路径,例如:

/full/path/lolsed_bullsh.png

I'm having a hard time matching and capturing these.我很难匹配和捕捉这些。 currently i'm trying variations of:目前我正在尝试以下变化:

cat myfile.txt| sed s/\(.+\)\.png/\/full\/path\/\1/g | ack /full/path

I think sed has some regex or capture group behavior I'm not understanding我认为 sed 有一些我不理解的正则表达式或捕获组行为

In your regex change + with * :在您的正则表达式中使用*更改+

sed -E "s/(.*)\.png/\/full\/path\/\1/g" <<< "lolsed_bulsh.png"

It prints:它打印:

/full/path/lolsed_bulsh

NOTE: The non standard -E option is to avoid escaping ( and )注意:非标准-E选项是为了避免转义()

Save yourself some escaping by choosing a different separator (and -E option), for example:通过选择不同的分隔符(和-E选项)来节省一些转义,例如:

cat myfile.txt | sed -E "s|(..*)\.png|/full/path/\1|g" | ack /full/path

Note that where supported, the -E option ensures ( and ) don't need escaping.请注意,在支持的情况下, -E选项确保()不需要转义。

sed uses POSIX BRE, and BRE doesn't support one or more quantifier + . sed使用 POSIX BRE,而BRE 不支持一个或多个量词+ The quantifier + is only supported in POSIX ERE .量词+在 POSIX ERE 中受支持 However, POSIX sed uses BRE and has no option to switch to ERE .但是, POSIX sed 使用 BRE 并且没有切换到 ERE 的选项

Use ..* to simulate .+ if you want to maintain portability.如果要保持可移植性,请使用..*模拟.+

Or if you can assume that the code is always run on GNU sed, you can use GNU extension \+ .或者,如果您可以假设代码始终在 GNU sed 上运行,您可以使用 GNU 扩展名\+ Alternatively, you can also use the GNU extension -r flag to switch to POSIX ERE.或者,您也可以使用 GNU 扩展-r标志切换到 POSIX ERE。 The -E flag in higuaro's answer has been tagged for inclusion in POSIX.1 Issue 8 , and exists in POSIX.1-202x Draft 1 (June 2020) . higuaro 的答案中的-E标志已被标记为包含在 POSIX.1 Issue 8中,并且存在于POSIX.1-202x Draft 1 (June 2020)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM