Tell me more ×
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

2 Answers

up vote 36 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.

share|improve this answer
1  
aha! It was the missing -e switch that got me. – sequoia mcdowell Sep 12 '11 at 14:44
8  
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

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

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.