So replacing all tabs in a file with spaces is not hard.
In vim for example, I can do %s/\t/ /gc

And if I want to replace the ones at the beginning of each line, not the one in the middle I can do %s/^\t/ /gc

But if there are line with one and lines with more tabs at the beginning, and lines with tabs in the middle, and I want to replace each tab in the beginning of a line with spaces to keep the indentation structure of the file, that is what I don't know how to do.

In vim or sed or generally using regular expressions.


You can use the evaluation register to replace any number of tabs with the appropriate number of spaces. For example:

:s/^\t\+/\=repeat('    ',len(submatch(0)))


:s/                                         " Replace
   ^                                        " At the start of a line
    \t\+                                    " One or more tabs
        /\=                                 " With the following evaluated as vimscript:
           repeat('    ',len(submatch(0)))  " 4 spaces times the length of the previously matched string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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