Created
December 1, 2013 22:29
-
-
Save tueda/7741717 to your computer and use it in GitHub Desktop.
A script to remove trailing whitespace from text files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/sh | |
# | |
# @file rstrip.sh | |
# | |
# Removes trailing whitespace from text files. | |
# | |
# Example: | |
# rstrip.sh *.c | |
# rstrip.sh -r . # all files in the current directory | |
# | |
set -e | |
prog=`basename "$0"` | |
# Command line options. | |
opt_dry_run=false | |
opt_help=false | |
opt_recursive=false | |
# Checks if $1 is a text file. | |
is_text() { | |
file "$1" | grep text >/dev/null | |
} | |
# Wraps "mktemp -d $1XXXXXXXXXX" | |
mktemp_d() {( | |
umask 077 | |
{ | |
# Use mktemp if available. | |
dir=`mktemp -d "$1XXXXXXXXXX" 2>/dev/null` && [ -d "$dir" ] | |
} || { | |
# Fall back on mkdir. | |
dir= | |
i=0 | |
while [ $i -lt 100 ]; do | |
next_dir=$1$$$i$RANDOM$RANDOM | |
if mkdir "$next_dir" >/dev/null 2>&1; then | |
dir=$next_dir | |
break | |
fi | |
i=`expr $i + 1` | |
done | |
[ "x$dir" != x ] && [ -d "$dir" ] | |
} || { | |
echo "$prog: error: failed to create a temporary directory" >&2 | |
exit 1 | |
} | |
echo "$dir" | |
)} | |
# Parse the command line options. | |
for opt_arg do | |
case $opt_arg in | |
-h|--help) | |
opt_help=: | |
;; | |
-n|--dry-run) | |
opt_dry_run=: | |
;; | |
-r|--recursive) | |
opt_recursive=: | |
;; | |
--) | |
shift | |
break | |
;; | |
-*) | |
echo "$prog: error: unknown option \"$opt_arg\"" >&2 | |
exit 1 | |
;; | |
*) | |
break | |
;; | |
esac | |
shift | |
done | |
[ $# -eq 0 ] && opt_help=: | |
# Help message. | |
if $opt_help; then | |
cat <<END | |
Usage: $prog [options...] [--] files... | |
Options: | |
-h, --help | |
Print this message and exit. | |
-n, --dry-run | |
Do not replace any files. | |
-r, --recursive | |
Replcae files in subdirectories recursively. | |
END | |
exit 0 | |
fi | |
# Create a working directory. | |
tmpdir=`mktemp_d "${TMPDIR:-/tmp}/tmp"` | |
trap 'rm -rf "$tmpdir"' 0 1 2 13 15 | |
# Removes trailing spaces from the file $1 using $tmpdir. | |
remove_trailing_spaces() {( | |
if [ -d "$1" ]; then | |
if $opt_recursive; then | |
for f in "$1"/*; do | |
remove_trailing_spaces "$f" | |
done | |
fi | |
elif is_text "$1"; then | |
file=$1 | |
tmp=`basename "$file"` | |
tmp="$tmpdir/$tmp" | |
cp -p "$file" "$tmp" # copy for the file permission | |
sed 's/\s*$//g' "$file" >"$tmp" | |
if diff "$1" "$tmp" >/dev/null; then | |
echo "Checked $file" | |
else | |
$opt_dry_run || mv "$tmp" "$file" | |
echo "Replaced $file" | |
fi | |
fi | |
)} | |
for f; do | |
remove_trailing_spaces "$f" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment