杂:使⽤Shell判断⽂件换⾏符(LFCRLF)前提:⽂件最后⼀⾏有换⾏符
第⼀步:以⼆进制⽅式取得⽂件最后两个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"shell代码
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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。