Skip to content

Instantly share code, notes, and snippets.

@markusfisch
Last active January 15, 2016 17:12
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 markusfisch/2481112 to your computer and use it in GitHub Desktop.
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
#!/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