Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

4 Answers 4

up vote 63 down vote accepted

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

share|improve this answer
2  
aha! It was the missing -e switch that got me. –  sequoia mcdowell Sep 12 '11 at 14:44
12  
I also had to add '-r' switch which enables extended regex's to make sed recognize '\s' as space. –  HUB May 16 '12 at 15:12
4  
With Apple's sed I had to use [[:space:]] because \s did not work for me. Perhaps \s is a GNU sed extension? –  Jared Beck Jun 17 '13 at 23:24
    
@JaredBeck thanks, was running out of ideas why my simple regex wasnt working.. This is lame, I thought \s was standard extended regex.. Also -r doesnt work and -E did squat –  Karthik T Sep 11 '13 at 4:58
    
Thanks for the feedback. I updated the answer with links to the POSIX standard. –  mrucci Sep 11 '13 at 8:32

This works on MacOS 10.8:

sed -E "s/[[:space:]]+/ /g"
share|improve this answer
1  
do you know if this works on all Linux distros ? –  amphibient Feb 6 at 17:26
    
Not generally, GNU sed won't have -E. From the BSD sed man page: "The -E, -a and -i options are non-standard FreeBSD extensions and may not be available on other operating systems." –  Brad Koch Mar 18 at 21:19

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.

share|improve this answer
1  
So for the particular need here, with an older sed, you could do: $ sed 's/[XZ][XZ][XZ][XZ]*/ /g' inputfile where X is a tab and Z is a space. –  Marnix A. van Ammers Apr 12 '10 at 15:08
sed 's/[ \t]*/"space or tab"/'
share|improve this answer
    
Is this guaranteed to work on any version of sed on any system? If not it might be worth mentioning where this does work in a similar fashion as the other answers, just so we know the limitations and where this might not have the intended result. –  Mokubai Jul 22 at 20:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.