[英]Regex matches but sed fails replace
I am having a tricky regex issue我有一个棘手的正则表达式问题
I have the string like below我有像下面这样的字符串
some_Name _ _Bday Date Comm.txt
And here is my regex to match the spaces and underscore这是我的正则表达式来匹配空格和下划线
\_?\s\_?
Now when i try to replace the string using sed and the above regex
echo "some_Name _ _Bday Date Comm.txt" | sed 's/\_?\s\_?/\_/g'
The output i want is我想要的输出是
some_Name_Bday_Date_Comm.txt
Any ideas on how do i go about this ?关于如何解决这个问题的任何想法?
You are using a POSIX BRE regex engine with the \\_?\\s\\_?
您正在使用带有
\\_?\\s\\_?
的 POSIX BRE 正则表达式引擎\\_?\\s\\_?
pattern that matches a _?
匹配
_?
, a whitespace (if your sed
supports \\s
shorthand) an a _?
, 一个空格(如果您的
sed
支持\\s
简写)一个 a _?
substring, ie the ?
子串,即
?
are treated as literal question mark symbols.被视为字面问号符号。
You may use您可以使用
sed -E 's/[[:space:]_]+/_/g'
sed 's/[[:space:]_]\{1,\}/_/g'
See online sed
demo查看在线
sed
演示
The [[:space:]_]+
POSIX ERE pattern (enabled with -E
option) will match one or more whitespace or underscore characters. [[:space:]_]+
POSIX ERE 模式(使用-E
选项启用)将匹配一个或多个空格或下划线字符。
The POSIX ERE +
quantifier can be written as \\{1,\\}
in POSIX BRE. POSIX ERE
+
量词在 POSIX BRE 中可以写为\\{1,\\}
。 Also, if you use a GNU sed
, you may use \\+
in the second sed
command.此外,如果您使用 GNU
sed
,则可以在第二个sed
命令中使用\\+
。
This might work for you (GNU sed):这可能对你有用(GNU sed):
sed -E 's/\s(\s*_)*/_/g' file
This will replace a space followed by zero or more of the following: zero or more spaces followed by an underscore.这将替换后跟零个或多个以下内容的空格:零个或多个空格后跟下划线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.