Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How does one convert 4 spaces into 2 spaces with sed? Is it possible?

I found this but it converts tab to spaces:

sed -r ':f; s|^(\t*)\s{4}|\1\t|g; t f' file

share|improve this question
up vote 9 down vote accepted

The script you posted converts 4*n spaces to n tabs, only if those spaces are preceded only by tabs.

If you want to replace 4 spaces by 2 spaces, but only in indentation, while it's possible to do it with sed, I recommend Perl instead.

perl -ne 's{^( {4}*)}{"  " x (2*len($1)/4)}e' file

In sed:

sed -e 's/^/~/' -e ': r' -e 's/^\( *\)~    /\1  ~/' -e 't r' -e 's/~//' file

You may want to use indent instead.

share|improve this answer

Doesn't the straightforward way work:

sed -r 's/ {4}/  /g'

If not, post some input where it fails.

share|improve this answer

If only leading spaces are to be converted:

sed 'h;s/[^ ].*//;s/    /  /g;G;s/\n *//'

With comments:

sed '
  h; # save a copy of the pattern space (filled with the current line)
     # onto the hold space
  s/[^ ].*//; # remove everything starting with the first non-space
              # from the pattern space. That leaves the leading space
              # characters
  s/    /  /g; # substitute every sequence of 4 spaces with 2.
  G; # append a newline and the hold space (the saved original line) to
     # the pattern space.
  s/\n *//; # remove that newline and the indentation of the original
            # line that follows it'

Also look at vim's 'ts' setting and :retab command

share|improve this answer
Using your vim solution, is there a way to batch edit several files like that with vim? Otherwise i'm guessing i would have to create a macro? – chrisjlee Sep 10 '12 at 15:03
Note that 'ts' and :retab are not solutions to the question, but are related and may help address your overall goal. You can do vim -- *.c, :set ts=... and then :argdo retab or :argdo retab!. See also the 'sw' option and vim's own indenting capabilities. – Stéphane Chazelas Sep 10 '12 at 15:15

Your Answer


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.