为什么我在 sed 's/[a-z]*/(&)/g' 中得到空格 [英] why am I getting spaces in sed 's/[a-z]*/(&)/g'
问题描述
我想为所有单词添加括号我用过
I want to add parenthesis to all words I used
sed 's/[a-z]*/(&)/g'
输入文件.txt
hola crayola123456
abc123456
但是我选择了所有空格
(hola) (crayola)1()2()3()4()5()6()
(abc)1()2()3()4()5()6()
我不应该只得到单词吗?我正在使用 mac sed
shouldn't I be getting only the words? I am using mac sed
谢谢
推荐答案
原因是您使用的正则表达式可以匹配空字符串.[a-z]*
可以匹配字符前的任何空格,因为正则表达式看到"(即检查)这些位置.您需要将 *
(匹配 零 个或多个出现)替换为 +
量词(匹配 一个 或多个字符).
The reason is that you are using a regex that can match an empty string. [a-z]*
can match any empty space before a char since regex "sees" (i.e. checks) these positions. You need to replace the *
(matching zero or more occurrences) with +
quantifier (to match one or more characters).
以下是如何在 GNU sed 中实现此功能的示例:
Here is an example of how this can be implemented in GNU sed:
echo "hola crayola123456" | sed 's/[a-z]\+/(&)/g'
查看在线演示
在 Mac 上,根据 anubhava 的评论,您需要使用 E
选项并使用未转义的 +
:
On Mac, as per anubhava's comment, you need to use E
option and use an unescaped +
:
echo "hola crayola123456" | sed -E 's/[a-z]+/(&)/g'
这篇关于为什么我在 sed 's/[a-z]*/(&)/g' 中得到空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!