αԋɱ*_*cαη 4 sed regular-expression
输入
[*] 111, 22, 33, 44
Run Code Online (Sandbox Code Playgroud)
输出
111,22,33,44
Run Code Online (Sandbox Code Playgroud)
使用sed
命令sed 's/^\[\*\][[:space:]]*//' file
能够显示输出,111, 22, 33, 44
这意味着空间仍然存在。
那么正确的sed
命令是什么?
简短的回答是,这应该做你想做的:
sed 's/[][*]\|[[:space:]]//g'
Run Code Online (Sandbox Code Playgroud)
像这样测试它:
echo '[*] 111, 22, 33, 44' | sed 's/[][*]\|[[:space:]]//g'
Run Code Online (Sandbox Code Playgroud)
输出:
111,22,33,44
Run Code Online (Sandbox Code Playgroud)
更长的解释如下。
您的表达式缺失的关键因素是使用该g
命令执行全局替换。如果没有此命令,则只会替换每行上的第一个匹配项。
我的解决方案中最违反直觉的一点(在我看来)是如何在字符类中包含方括号。为此,我们参考sed 手册:
Run Code Online (Sandbox Code Playgroud)‘]’ ends the bracket expression if it’s not the first list item. So, if you want to make the ‘]’ character a list item, you must put it first.
有关该主题的进一步讨论,请参阅以下有关 SeverFault 的帖子:
或者,您可以使用您的表达式并将其通过管道传输到另一个sed
命令中,例如:
‘]’
ends the bracket expression if it’s not the first list item.
So, if you want to make the ‘]’ character a list item, you must put it first.
Run Code Online (Sandbox Code Playgroud)