Created
September 18, 2017 20:11
-
-
Save gburgett/73043f528da78f950a8b8971c4d6c1ae to your computer and use it in GitHub Desktop.
Expand tabs to spaces in all found files
This file contains 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/bash | |
COLOR_NC='\033[0m' # No Color | |
COLOR_LIGHT_GREEN='\033[1;32m' | |
usage() { | |
echo "$0 <files glob> | |
expand tabs to spaces in given files, printing names of files that would change. | |
" && \ | |
grep " .)\ #" $0; exit 0; | |
} | |
SPACES=2 | |
while getopts ":hrt:" arg; do | |
case $arg in | |
t) # Number of spaces to replace each tab with | |
SPACES=${OPTARG} | |
;; | |
r) # Expand tabs in-place, actually replacing files. | |
REPLACE=true | |
;; | |
h | *) # Display help. | |
usage | |
exit 0 | |
;; | |
esac | |
done | |
shift $(($OPTIND - 1)) | |
FILES=$1; | |
[[ -z "$FILES" ]] && usage && exit -1; | |
FOUND_FILES=$(find . -name $FILES -not -path '*/\.*') | |
WORK_DIR=`mktemp -d` | |
# deletes the temp directory | |
function cleanup { | |
rm -rf "$WORK_DIR" | |
} | |
# register the cleanup function to be called on the EXIT signal | |
trap cleanup EXIT | |
NUM_LINES=0 | |
while read -r line; do | |
if [[ -z "$line" ]]; then | |
continue | |
fi | |
echo "line: $line" | |
mkdir -p `dirname $WORK_DIR/$line` | |
expand -t 2 $line > $WORK_DIR/$line | |
HAS_DIFF=`diff -q $line $WORK_DIR/$line` | |
if [[ ! -z "$HAS_DIFF" ]]; then | |
if [[ $REPLACE ]]; then | |
mv $WORK_DIR/$line $line | |
echo -e "$line ${COLOR_LIGHT_GREEN}overwritten${COLOR_NC}" | |
else | |
echo $line | |
NUM_LINES=$((NUM_LINES+1)) | |
fi | |
fi | |
done <<< "$FOUND_FILES" | |
exit $NUM_LINES |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment