sed convert 4 spaces to 2

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 -pe 's{^((?: {4})*)}{" " x (2*length($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.


Doesn't the straightforward way work:

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

If not, post some input where it fails.


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

Tags:

Sed