Skip to content

Instantly share code, notes, and snippets.

@malesch
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malesch/676b203a584399c8016e to your computer and use it in GitHub Desktop.
Save malesch/676b203a584399c8016e to your computer and use it in GitHub Desktop.
Strip trailing whitespaces in project
#!/bin/bash
###########################################################
#
# Strip all trailing whitespaces and normalize line endings
# (\n [0x0A]).
#
# Due to RegEx problems with the standard sed under OS X I
# use gnu-sed. Install gnu-sed before, e.g. with brew:
# > brew install gnu-sed
#
###########################################################
# Files to strip, searched using the 'find' command
declare -a files_to_strip=(
"*.rb"
"*.js"
"*.coffee"
"*.scss"
"*.css"
"*.slim"
"*.erb"
"*.yml"
"*.xml"
"*.cap"
"*.rake"
"*.txt"
"*.rdoc"
"Gemfile"
"Rakefile"
"config.ru"
)
if [ "$(uname -s)" == "Darwin" ]
then
sed_cmd="gsed"
else
sed_cmd="sed"
fi
for i in "${files_to_strip[@]}"
do
echo "Strip trailing whitespaces on '${i}'"
`find . -name $i -type f -exec ${sed_cmd} -i -E 's/[[:blank:]]*\r?$//g' {} \;`
done
@svoop
Copy link

svoop commented Dec 3, 2014

Sieht soweit ganz gut aus. Kannst du noch einbauen, dass genau ein "\n" am Ende des Files garantiert ist?

@svoop
Copy link

svoop commented Dec 3, 2014

Und wenn du gerade so gut im Schuss bist: Könntest du noch ein Script schreiben, das feststellt, ob ein einzelnes File die Kriterien (no trailing whitespace, \n at file end) erfüllt oder nicht?

Bitte achte darauf, dass die Bash Commands in Linux und Mac OS X funktionieren. sed hat in den beiden OSes abweichende Argumente.

@svoop
Copy link

svoop commented Dec 3, 2014

By the way: *.cap ist doppelt gelistet.

@malesch
Copy link
Author

malesch commented Dec 4, 2014

  • Liste alle Dateien, die gegen die EOL Regel verstossen (ob es ein \r\n hat):

grep -Rl -e '\r$' *

  • Liste der Dateien, die "Trailing Whitespaces" haben:

grep -Rl -E '[[:blank:]]+\r?$' *

  • Script, das testet, ob eine Datei die obigen Bedingungen erfüllt:
#!/bin/bash

IFS=","

declare -a violations
violations+=(`grep -q -E '\r$' $1 && echo "EOL"`)
violations+=(`grep -q -E '[[:blank:]]+\r?$' $1 && echo 'trailing whitespaces'`)

if [ ${#violations} -ne 0 ]
then
    echo "$1 is INVALID (Reason: ${violations[*]})"
else
  echo "$1 is clean"
fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment