logo

tested on openbsd 6.3

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

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

$ grep -rIl '[[:space:]]$' .
file-with-trailing-spaces.txt
$

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:]]$'
file-with-trailing-spaces.txt
$

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 \
    trailing-space,-space-before-tab,indent-with-non-tab,cr-at-eol
$

Add pre-commit hook to .git/hooks:

#!/bin/sh
exec git diff-index --check --cached HEAD --

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