I run several substitution commands as the core of a colorize script for maven. One of the sed
commands uses a regular expression which works find in the shell as discussed here. The current (not working) implementation can be found here.
我运行几个替换命令作为maven的彩色脚本的核心。其中一个sed命令使用了一个正则表达式,该表达式在这里讨论。在这里可以找到当前(不工作的)实现。
When I include one of the variants of the command into the script different behavior occurs:
当我将命令的一个变体包含到脚本中时,会发生不同的行为:
Variant 1:
版本1:
$ sed -re "s/([a-zA-Z0-9./\\ :-]+)/\1/g"
Adapted to the script:
适应了脚本:
-re "s/WARNING: ([a-zA-Z0-9./\\ :-]+)/${warn}WARNING: \1${c_end}/g" \
Error: The shell outputs the same information as if I would type $ sed
. Strange!?
错误:shell输出相同的信息,就好像我要输入$ sed。奇怪! ?
Variant 2:
版本2:
$ sed -e "s/\([a-zA-Z0-9./\\ :-]\+\)/\1/g"
Adapted to the script:
适应了脚本:
-e "s/WARNING: \([a-zA-Z0-9./\\ :-]\+\)/${warn}WARNING: \1${c_end}/g" \
Error:
错误:
sed: -e expression #7, char 59: invalid reference \1 on `s' command's RHS
sed: -e表达式#7,char 59:对's '命令的RHS无效引用\1。
3 个解决方案
#1
15
Don't you need to actually capture for that to work? i.e. for variant 2:
难道你不需要抓住这个机会去工作吗?例如变种2:
-r -e "s/WARNING: (\([a-zA-Z0-9./\\ :-]\+\))/${warn}WARNING: \1${c_end}/g" \
(Note: untested)
(注:未测试)
Without the -r argument back-references (like \1) won't work.
如果没有-r参数,反向引用(如\1)不会起作用。
#2
39
This error is common for parentheses that are not escaped. Escape them and try again.
这个错误在没有转义的括号中是常见的。逃离他们,再试一次。
For example:
例如:
/^$/b
:loop
$!{
N
/\n$/!b loop
}
s/\n(.)/\1/g
Should be escaped with backslashes before each parenthesis:
在每个括号之前,应该用反斜杠来转义:
/^$/b
:loop
$!{
N
/\n$/!b loop
}
s/\n\(.\)/\1/g
#3
4
You need escape the /
after the .
你需要逃离。
sed -e "s/\([a-zA-Z0-9.\/\\ :-]\+\)/\1/g"
Or if you don't want to worry about escaping, use |
或者如果你不想担心逃跑,用|。
sed -e "s|\([a-zA-Z0-9./\\ :-]\+\)|\1|g"
EDIT:
编辑:
sed -e "s|WARNING: \([a-zA-Z0-9.-/\\ :]+\)|${warn}WARNING: \1${c_end}|g"
#1
15
Don't you need to actually capture for that to work? i.e. for variant 2:
难道你不需要抓住这个机会去工作吗?例如变种2:
-r -e "s/WARNING: (\([a-zA-Z0-9./\\ :-]\+\))/${warn}WARNING: \1${c_end}/g" \
(Note: untested)
(注:未测试)
Without the -r argument back-references (like \1) won't work.
如果没有-r参数,反向引用(如\1)不会起作用。
#2
39
This error is common for parentheses that are not escaped. Escape them and try again.
这个错误在没有转义的括号中是常见的。逃离他们,再试一次。
For example:
例如:
/^$/b
:loop
$!{
N
/\n$/!b loop
}
s/\n(.)/\1/g
Should be escaped with backslashes before each parenthesis:
在每个括号之前,应该用反斜杠来转义:
/^$/b
:loop
$!{
N
/\n$/!b loop
}
s/\n\(.\)/\1/g
#3
4
You need escape the /
after the .
你需要逃离。
sed -e "s/\([a-zA-Z0-9.\/\\ :-]\+\)/\1/g"
Or if you don't want to worry about escaping, use |
或者如果你不想担心逃跑,用|。
sed -e "s|\([a-zA-Z0-9./\\ :-]\+\)|\1|g"
EDIT:
编辑:
sed -e "s|WARNING: \([a-zA-Z0-9.-/\\ :]+\)|${warn}WARNING: \1${c_end}|g"