romanzolotarev.com: support and follow me on Mastodon and Twitter

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:]]$' .
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.


Thanks to Tim Chase for performance hints.