up vote 11 down vote favorite
3
share [g+] share [fb]

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?

link|improve this question

feedback

2 Answers

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

link|improve this answer
aha! It was the missing -e switch that got me. – sequoia mcdowell Sep 12 '11 at 14:44
feedback

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.

link|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
feedback

Your Answer

 
or
required, but never shown

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