bash 为什么这个 sed 命令与空格不匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12324403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does this sed command not match whitespace?
提问by Byron Hawkins
This bash script is supposed to remove leading whitespace from grep results:
这个 bash 脚本应该从 grep 结果中删除前导空格:
#!/bin/bash
grep --color=always $@ | sed -r -e's/:[[:space:]]*/:/'
But it doesn't match the whitespace. If I change the substitution text to "-", that shows up in the output, but it still never removes the whitespace. I've tried it without the "*", escaping the "*", with "+", etc, but nothing works. Does anyone know why not?
但它与空格不匹配。如果我将替换文本更改为“-”,它会显示在输出中,但它仍然不会删除空格。我试过没有“*”,转义“*”,用“+”等,但没有任何效果。有谁知道为什么不?
(I'm using sed version 4.2.1 on Ubuntu 12.04.)
(我在 Ubuntu 12.04 上使用 sed 版本 4.2.1。)
Thanks all, this is my modified script, which shows grep color and also trims leading blanks:
谢谢大家,这是我修改过的脚本,它显示了 grep 颜色并修剪了前导空格:
#!/bin/bash
grep --color=always $@ | sed -r -e's/[[:space:]]+//'
回答by perreal
You need to remove the --color option for this to work. The color codes confuse sed:
您需要删除 --color 选项才能使其工作。颜色代码混淆了 sed:
grep $@ | sed -r -e's/:[[:space:]]*/:/'
回答by ruakh
The color information output by greptakes the form of special character sequences (see answers to this StackOverflow question), so if the colon is colored and the whitespace isn't, or vice versa, then that means that one of these character sequences will be between them, so sedwill not see them as adjacent characters.
输出的颜色信息grep采用特殊字符序列的形式(请参阅此 StackOverflow 问题的答案),因此如果冒号是彩色的而空白不是,反之亦然,则意味着这些字符序列之一将介于它们,因此sed不会将它们视为相邻字符。
回答by Hunter
The character class \s will match the whitespace characters and
字符类 \s 将匹配空白字符和
For example:
例如:
$ sed -e "s/\s\{3,\}/ /g" inputFile
will substitute every sequence of at least 3 whitespaces with two spaces.
将用两个空格替换至少 3 个空格的每个序列。
回答by AnBisw
grep --color=always $@ |sed 's/^ //g'
Removes leading white spaces.
删除前导空格。

