Tested on OpenBSD 6.3.

Find and remove whitespaces with grep(1) and sed(1)

TL;DR: Checkout my fws, tws, and .gitconfig.

Find lines with trailing spaces in all non-binary files (recursively starting from the current directory).

$ grep -rIl '[[:space:]]$' .

Find and remove those spaces.

$ grep -rIl '[[:space:]]$' . | xargs sed -i 's/[[:space:]]*$//'

A slightly faster version

Exclude *.git directories and use all CPU cores.

$ find . \
    \( -type d -name '*.git' -prune \) -o \
    \( -type f -print0 \) |
xargs -0 \
    -P "$(sysctl -n hw.ncpu)" \
    -r 2>/dev/null grep -Il '[[:space:]]$'

Configure vi

Add to .exrc:

map gt mm:%s/[[:space:]]*$//^M`m

Where ^M is the actual CR character: press ^V, then <Enter>.

Configure git

Git can detect whitespaces.

$ git config --global core.whitespace \

Add pre-commit hook to .git/hooks:

exec git diff-index --check --cached HEAD --

If there are whitespace errors, it prints the file names and fails.

Thanks to Tim Chase for performance hints.