Sed (in bash) works with [\ t] but not with \ s?

I want to do a search - replace anything containing spaces on the bash command line, and I assumed sed would be the easiest way.

Usage [ \t]

denoting tab or space to match whitespace works as intended:

echo "abc xyz" | sed "s/[ \t]xyz/123/"


But using \s

instead [ \t]

, to my surprise,

echo "abc xyz" | sed "s/\sxyz/123/"
abc xyz


I'm new to bash, so I might be missing something trivial, but no matter what I do, I can't get it to work. Using \\s

instead \s

, using single quotes ( '

instead of "

), putting the whitespace marker in square brackets (like, [\s]

or even [\\s]

) doesn't help anything.?

(edit) if it differs from one sed / bash version to another: I am working on OS X here.

Also, I noticed that when I add +

after the whitespace part [ \t]

to capture multiple space / tab characters as needed, it doesn't work anymore ... ??

echo "abc xyz" | sed "s/[ \t]+xyz/123/"
abc xyz


(again, using \+

instead +

and single quotes else fails, instead of double quotes)


source to share

2 answers

As seen in SuperUser How to match spaces in sed? :

For POSIX compliance, use the character class [[: space:]] instead of \ s, as the latter is a GNU sed extension

So, you're probably using a non-GNU version sed

, so \s

doesn't work for you.

You have two solutions:

  • To use

    (space) and \t

    together as you did.
  • Use [[:space:]]



echo 'abc xyz<>abcxyz' | sed 's/[[:space:]]xyz/123/g'
echo 'abc xyz<>abcxyz' | sed "s/[[:space:]]xyz/123/g"


doesn't work on very old sed version, but works fine on GNU sed as a posix complaint (AIX, ...)



All Articles