Replace each tab ONLY at the beginning of each line with spaces

sedvimwhitespace

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.

Best Answer

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)))

Explanation:

: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
Related Question