sed 删除行中的特殊字符和空格

αԋɱ*_*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命令是什么?

iga*_*gal 6

简短的回答是,这应该做你想做的:

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 手册

‘]’
    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)

有关该主题的进一步讨论,请参阅以下有关 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)