bash MacOSX 10.9.5 上的 Sed 错误“\1 未在 RE 中定义”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28072190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:13:20  来源:igfitidea点击:

Sed error "\1 not defined in the RE" on MacOSX 10.9.5

regexmacosbashsed

提问by mummybot

I am trying to build a generic formatter for my MP3 file names (very important) with bash, and a large part of this is being able to move text around using regex variables. For example I am trying to remove the parentheses () from around the ft. Kevin Parker.

我正在尝试使用 bash 为我的 MP3 文件名(非常重要)构建一个通用格式化程序,其中很大一部分是能够使用正则表达式变量移动文本。例如,我试图从 ft. Kevin Parker 周围删除括号 ()。

oldfilename="Mark Ronson - 02 Summer Breaking (ft. Kevin Parker).mp3"

newfilename=$(echo $oldfilename | sed -E "s/ft.\(*\)/ft./g")

This causes the error:

这会导致错误:

sed: 1: "s/ft.\(*\)/gt./g":  not defined in the RE

I have tried escaping and not escaping the (), and adding and removing the -E switch as recommended by .bash_profile sed: \1 not defined in the RE. Help?!

我试过转义而不是转义 (),并按照.bash_profile sed: \1 not defined in the RE 的建议添加和删除 -E 开关。帮助?!

回答by Jonathan Leffler

If you use -E, then \(and \)are actual parentheses; to capture, you'd use just (and ). Here, you want to remove parentheses, so you need to match a literal (, capture the content up to the next )and match but not capture the close ), and replace the whole lot with just the capture:

如果您使用-E, 则\(\)是实际的括号;要捕获,您只需使用()。在这里,您想要删除括号,因此您需要匹配一个字面量(,将内容捕获到下一个)并匹配但不捕获 close ),并仅用捕获替换整个批次:

newfilename=$(echo "$oldfilename" | sed -E "s/\((ft[^)]*)\)//g")

Or, for amusement value, you can do it without -E:

或者,为了娱乐价值,您可以不使用-E

newfilename=$(echo "$oldfilename" | sed -e "s/(\(ft[^)]*\))//g")

(The -eis a cheat; it just identifies an expression that's part of the sedscript. It does not mean 'opposite of -E' and you could have both -Eand one or more -e …arg…argument pairs.)

(这-e是作弊;它只是标识作为sed脚本一部分的表达式。它并不意味着“与 ”相反,-E您可以同时拥有-E一个或多个-e …arg…参数对。)

Note that the file name should be in quotes unless you are deliberately ensuring that any leading or trailing blanks are removed, and any internal tabs or newlines are replaced with blanks, and any multiple blanks in the name are replaced with a single tab. If you do want the 'space normalization', then leaving the quotes out is better.

请注意,文件名应该用引号引起来,除非您特意确保删除任何前导或尾随空格,并且任何内部制表符或换行符都被替换为空格,并且名称中的任何多个空格都被替换为单个制表符。如果您确实想要“空间规范化”,那么最好不要使用引号。