How to remove trailing whitespace of all files recursively?

前端 未结 15 1987
难免孤独
难免孤独 2020-12-07 06:58

How can you remove all of the trailing whitespace of an entire project? Starting at a root directory, and removing the trailing whitespace from all files in all folders.

15条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 07:47

    ex

    Try using Ex editor (part of Vim):

    $ ex +'bufdo!%s/\s\+$//e' -cxa **/*.*
    

    Note: For recursion (bash4 & zsh), we use a new globbing option (**/*.*). Enable by shopt -s globstar.

    You may add the following function into your .bash_profile:

    # Strip trailing whitespaces.
    # Usage: trim *.*
    # See: https://stackoverflow.com/q/10711051/55075
    trim() {
      ex +'bufdo!%s/\s\+$//e' -cxa $*
    }
    

    sed

    For using sed, check: How to remove trailing whitespaces with sed?

    find

    Find the following script (e.g. remove_trail_spaces.sh) for removing trailing whitespaces from the files:

    #!/bin/sh
    # Script to remove trailing whitespace of all files recursively
    # See: https://stackoverflow.com/questions/149057/how-to-remove-trailing-whitespace-of-all-files-recursively
    
    case "$OSTYPE" in
      darwin*) # OSX 10.5 Leopard, which does not use GNU sed or xargs.
        find . -type f -not -iwholename '*.git*' -print0  | xargs -0 sed -i .bak -E "s/[[:space:]]*$//"
        find . -type f -name \*.bak -print0 | xargs -0 rm -v
        ;;
      *)
        find . -type f -not -iwholename '*.git*' -print0 | xargs -0 perl -pi -e 's/ +$//'
    esac
    

    Run this script from the directory which you want to scan. On OSX at the end, it will remove all the files ending with .bak.

    Or just:

    find . -type f -name "*.java" -exec perl -p -i -e "s/[ \t]$//g" {} \;
    

    which is recommended way by Spring Framework Code Style.

提交回复
热议问题