sed(以bash格式)可与[\ t]一起使用,但不能与\ s一起使用? [英] sed (in bash) works with [ \t] but not with \s?
问题描述
我想在bash命令行上搜索替换包含空格的内容,并且我认为sed是最简单的方法.
I want to search-replace something containing whitespace on a bash command line, and I assumed sed would be the easiest way to go.
使用[ \t]
表示制表符或空格以匹配空白,可以按预期工作:
Using [ \t]
denoting either tab or space, to match the whitespace, works as intended:
echo "abc xyz" | sed "s/[ \t]xyz/123/"
abc123
但是,用\s
代替[ \t]
却没有,令我惊讶的是:
But using \s
instead of [ \t]
does not, to my surprise:
echo "abc xyz" | sed "s/\sxyz/123/"
abc xyz
我对bash还是比较陌生,所以我可能会错过一些琐碎的事情,但是无论我做什么,我都无法使它正常工作.使用\\s
代替\s
,使用单引号('
代替"
),将空格标记放在方括号内(例如[\s]
甚至[\\s]
),似乎没有任何帮助.
I'm fairly new to bash so I might be missing something trivial, but no matter what I do, I can't get this to work. Using \\s
instead of \s
, using single quotes ('
instead of "
), putting the whitespace marker inside square brackets (like [\s]
or even [\\s]
), nothing seems to help..?
(编辑),以防一个sed/bash版本与另一个版本不同:我在这里使用OSX.
(edit) in case it differs from one sed / bash version to another: I'm working on OS X here.
此外,我注意到,当我在[ \t]
空格部分之后添加+
时,可以有选择地捕获多个空格/制表符(如果存在),那么它将不再起作用... ??
Additionally, I noticed that when I add a +
after the [ \t]
whitespace part, to optionally grab multiple space/tab characters if present, it doesn't work anymore either...??
echo "abc xyz" | sed "s/[ \t]+xyz/123/"
abc xyz
(同样,也尝试使用\+
而不是+
,并且用单引号代替双引号,无济于事)
(and again, also tried with \+
instead of +
, and single quotes instead of double quotes, nothing helps)
推荐答案
如SuperUser的如何在sed中匹配空格?:
As seen in SuperUser's How to match whitespace in sed?:
为了符合POSIX,请使用字符类[[:space:]]代替 \ s,因为后者是GNU sed扩展名
For POSIX compliance, use the character class [[:space:]] instead of \s, since the latter is a GNU sed extension
因此您可能正在运行非GNU sed
版本,因此\s
对您不起作用.
So you are probably running a non-GNU sed
version, hence \s
not working to you.
您有两种解决方案:
- 像您一样,同时使用
(空格)和
\t
. - 要使用
[[:space:]]
.
- To use
(space) and
\t
together, like you were doing. - To use
[[:space:]]
.
这篇关于sed(以bash格式)可与[\ t]一起使用,但不能与\ s一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!