How can I convert tabs to spaces in every file of a directory?

后端 未结 19 1291
既然无缘
既然无缘 2020-12-02 03:48

How can I convert tabs to spaces in every file of a directory (possibly recursively)?

Also, is there a way of setting the number of spaces per tab?

19条回答
  •  旧巷少年郎
    2020-12-02 03:54

    Use the vim-way:

    $ ex +'bufdo retab' -cxa **/*.*
    
    • Make the backup! before executing the above command, as it can corrupt your binary files.
    • To use globstar (**) for recursion, activate by shopt -s globstar.
    • To specify specific file type, use for example: **/*.c.

    To modify tabstop, add +'set ts=2'.

    However the down-side is that it can replace tabs inside the strings.

    So for slightly better solution (by using substitution), try:

    $ ex -s +'bufdo %s/^\t\+/  /ge' -cxa **/*.*
    

    Or by using ex editor + expand utility:

    $ ex -s +'bufdo!%!expand -t2' -cxa **/*.*
    

    For trailing spaces, see: How to remove trailing whitespaces for multiple files?


    You may add the following function into your .bash_profile:

    # Convert tabs to spaces.
    # Usage: retab *.*
    # See: https://stackoverflow.com/q/11094383/55075
    retab() {
      ex +'set ts=2' +'bufdo retab' -cxa $*
    }
    

提交回复
热议问题