How to remove trailing whitespace of all files recursively?

前端 未结 15 1956
难免孤独
难免孤独 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 08:04

    1) Many other answers use -E. I am not sure why, as that's undocumented BSD compatibility option. -r should be used instead.

    2) Other answers use -i ''. That should be just -i (or -i'' if preffered), because -i has the suffix right after.

    3) Git specific solution:

    git config --global alias.check-whitespace \
    'git diff-tree --check $(git hash-object -t tree /dev/null) HEAD'
    
    git check-whitespace | grep trailing | cut -d: -f1 | uniq -u -z | xargs -0 sed --in-place -e 's/[ \t]+$//'
    

    The first one registers a git alias check-whitespace which lists the files with trailing whitespaces. The second one runs sed on them.

    I only use \t rather than [:space:] as I don't typically see vertical tabs, form feeds and non-breakable spaces. Your measurement may vary.

提交回复
热议问题