仅用空格替换每行开头的每个制表符

Ali*_*Ali 6 vim sed whitespace

因此,用空格替换文件中的所有制表符并不难。
例如在 vim 中,我可以做到%s/\t/ /gc

如果我想替换每一行开头的那些,而不是我可以做的中间的 %s/^\t/ /gc

但是,如果开头有一行和多个制表符的行,中间有制表符的行,我想用空格替换行首的每个制表符以保持文件的缩进结构,即我不知道该怎么做。

在 vim 或 sed 中或一般使用正则表达式。

DJM*_*hem 8

您可以使用评估寄存器将任意数量的制表符替换为适当数量的空格。例如:

:s/^\t\+/\=repeat('    ',len(submatch(0)))
Run Code Online (Sandbox Code Playgroud)

解释:

: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
Run Code Online (Sandbox Code Playgroud)