Skip to content

Instantly share code, notes, and snippets.

@dfelton
Last active November 2, 2020 01:09
Show Gist options
  • Save dfelton/9b3d9384319b463ad19fad659bf3938a to your computer and use it in GitHub Desktop.
Save dfelton/9b3d9384319b463ad19fad659bf3938a to your computer and use it in GitHub Desktop.
Find / remove trailing spaces in file(s) in a directory

Linux compatible instructions for finding and/or removing trailing spaces from non-binary files.

# Finds all files in a directory that have lines which end in a space, and reports the line number(s)
# just change /PATH/TO/DIRECTORY to the actual directory you want
while read filename
do
grep -nHP ' $' $filename
done <<< "$(find /PATH/TO/DIRECTORY -type f -exec grep -lIm 1 -P ' $' {} \;)"
# for ~/.bashrc | ~/.zshrc | ~/.bash_profile | whatever your environment uses
findTrailingSpaces()
{
[ "$1" == "" ] && >&2 echo please provide path to directory && return;
[ ! -d "$1" ] && >&2 echo \"$1\" is not a directory && return;
while read filename
do
grep -nHP ' $' $filename
done <<< "$(find $1 -type f -exec grep -lIm 1 -P ' $' {} \;)"
}
removeTrailingSpaces()
{
[ "$1" == "" ] && >&2 echo please provide path to directory && return;
[ ! -d "$1" ] && >&2 echo \"$1\" is not a directory && return;
if [ "$2" != "NO_GIT" ]; then
( cd $1; git status > /dev/null 2>&1; exit $? )
if [ "$?" != "0" ]; then
>&2 echo \"$1\" is not directory of a git repository. exiting. if you meant to perform this pass \"NO_GIT\" as a secondary parameter to this function
return;
fi
fi
while read filename
do
sed -i 's/[ ]*$//' "$filename"
done <<< "$(find $1 -type f -exec grep -lIm 1 -P ' $' {} \;)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment