前提:文件最后一行有換行符
第一步:以二進制方式取得文件最后兩個byte。
last2=`tail -c 2 <your_file> | od -x -A n`
第二步:判斷最后兩個byte是否是'CRLF'
if [ $last2 = 0a0d -o $last2 = 0d0a ]
then
# Cheating! If the file ends in LFCR, it would incorrectly
# say that it is CRLF
echo File ends in CRLF
fi
另外,下面這種方法的原理,讓人百思不得其姐,
#重定向標准輸入
exec < <your_file>
read -r line
case $line in *$'\r') return 1;; *) return 0;; esac
原以為read加了-r就可以把$'\n'讀出來,實際上卻是用read把末尾的$'\n'先去掉,剩下的如果是$'\r'就認為是'CRLF'換行。
這個語句表明read一定會去掉末尾的$'\n'
PS:Shell里$'\r'和$'\n'就這么寫
完整代碼
#!/bin/bash
if [ $# -eq 0 ] ; then
echo "error : there is no para"
exit 1
fi
if [ ! -e $1 ] ; then
echo "file $1 is not exist"
exit 1
fi
last2=$(tail -c 2 "$1" | od -x -A n)
if [ $last2 = 0a0d -o $last2 = 0d0a ] ; then
echo "end with \\r\\n"
else
echo "end with \\n"
fi
遍歷文件夾版
#!/bin/bash
#func check CRLF bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
check_CRLF(){
last2=$(tail -c 2 "$1" | od -x -A n)
echo "last2 is $last2"
if [ $last2 = 0a0d -o $last2 = 0d0a ] ; then
echo "warning! file $1 end with \\r\\n"
else
echo "file $1 end with \\n"
fi
}
#func traverse folder bbbbbbbbbbbbbbbbbbbbbbbbbbbb
traverse_folder(){
# no para
if [ $# -eq 0 ]; then
exit 1
fi
# not folder
if [ ! -d $1 ]; then
exit 1
fi
# traversal
for files_or_folder in $1/*
do
# is file
if [ -f $files_or_folder ]; then
check_CRLF $files_or_folder
# is folder
elif [ -d $files_or_folder ]; then
traverse_folder $files_or_folder
else
exit 1
fi
done
}
#bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
if [ $# -eq 0 ] ; then
echo "error : there is no para"
exit
fi
traverse_folder $1
一句搞定版
find . -type f | xargs file | grep CRLF
