Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

3 Answers 3

up vote 8 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
add comment

Doesn't the straight forward way work:

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

If not, post some input where it fails.

share|improve this answer
add comment

If only leading spaces are to be converted:

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

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
add comment

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.