325

How can I match whitespace in sed? In my data I want to match all of 3+ subsequent whitespace characters (tab space) and replace them by 2 spaces. How can this be done?

Peter Smit
  • 9,636

6 Answers6

349

The character class \s will match the whitespace characters <tab> and <space>.

For example:

$ sed -e "s/\s\{3,\}/  /g" inputFile

will substitute every sequence of at least 3 whitespaces with two spaces.


REMARK: For POSIX compliance, use the character class [[:space:]] instead of \s, since the latter is a GNU sed extension. See the POSIX specifications for sed and BREs

mrucci
  • 10,234
119

This works on MacOS 10.8:

sed -E "s/[[:space:]]+/ /g"
some ideas
  • 1,338
17
sed 's/[ \t]*/"space or tab"/'
Zac
  • 446
14

Some older versions of sed may not recognize \s as a white space matching token. In that case you can match a sequence of one or more spaces and tabs with '[XZ][XZ]*' where X is a space and Z is a tab.

0

None of the above worked for me. Yet I found the simplest answer ever by using awk

user@~[]$ cat /tmp/file
/nospace/in/here
/this/one space
/well/seems we have spaces
user@~[]$ cat /tmp/file |awk 'NF>1'
/this/one space
/well/seems we have spaces
user@~[]$ 
-1

I don't know if it can help but I just did that :

MacBook-Pro-van-User:training user$ cat sed.txt

My name is Bob

MacBook-Pro-van-User:training user$ sed s/"My name is Bob"/"My Lastname is Montoya"/g sed.txt

My Lastname is Montoya

I just added "" in the command.