Last active
January 15, 2016 17:12
-
-
Save markusfisch/2481112 to your computer and use it in GitHub Desktop.
Deal with those needless carriage returns (CR) in text files from/for coworkers/friends on Windows
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
#!/usr/bin/env bash | |
readonly CR=$'\r' | |
# Add CR to given stream | |
add_cr() | |
{ | |
while read -r | |
do | |
echo "$REPLY"$CR | |
done | |
} | |
# Remove CR from given stream | |
rm_cr() | |
{ | |
while read -r | |
do | |
echo "${REPLY%$CR}" | |
done | |
} | |
# Returns true if the first line ends with a CR | |
has_cr() | |
{ | |
read -r && [[ $REPLY == *$CR ]] | |
} | |
# Fix CR for given files | |
# | |
# @param ... - files to process | |
fix_cr() | |
{ | |
local F T=".${0##*/}-$$" LOCK=${LOCK:-auto} | |
while [ -e "$T" ] | |
do | |
T="$T-$$" | |
done | |
for F | |
do | |
[ -r "$F" ] || { | |
echo "error: cannot read $F" >&2 | |
continue | |
} | |
local A=add_cr | |
if has_cr < "$F" | |
then | |
[ "$LOCK" == 'add' ] && continue | |
A=rm_cr | |
else | |
[ "$LOCK" == 'rm' ] && continue | |
fi | |
"$A" < "$F" > "$T" && mv "$T" "$F" | |
done | |
} | |
if [ "${BASH_SOURCE[0]}" == "$0" ] && (( $# > 0 )) | |
then | |
fix_cr "$@" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment