[英]bash multiple if statement inside loop is not working
I am new to bash scripting, I have a file and i want to check each line but it is not working.我是 bash 脚本的新手,我有一个文件,我想检查每一行,但它不起作用。
My bach script code我的 bach 脚本代码
declare -a arr
for (( i=0; i<${len}; i++ ))
do
if [[ ${arr[$i]} =~ ^[0-9]+$ ]]
then
echo ${arr[$i]}" numbr"
else
echo "No match"
fi
done
Why only last line is match ?为什么只有最后一行是 match ? is there any space or line break issue ?
是否有任何空格或换行符问题? suggest me some solution
建议我一些解决方案
Your file is saved in "DOS" format, with \\r\\n line endings.您的文件以“DOS”格式保存,以 \\r\\n 行结尾。
To convert to "unix" format:转换为“unix”格式:
dos2unix file.txt
# or, if that's not installed
sed -i 's/\r$//' file.txt
tangentially, I find the POSIX character class can describe what you want to match:切线地,我发现 POSIX 字符类可以描述您想要匹配的内容:
[[ ${arr[$i]} =~ ^[[:digit:]]+$ ]] && echo "${arr[i]} numbr"
[[ ${arr[$i]} =~ ^[[:alpha:]]+$ ]] && echo "${arr[i]} ltr only"
[[ ${arr[$i]} =~ ^[[:alnum:]]+$ ]] && echo "${arr[i]} both"
Your issue is MS-DOS line endings of $'\\r\\n'
instead of $'\\n'
only.您的问题是
$'\\r\\n'
而不是$'\\n'
MS-DOS 行尾。
You can remove the offending $'\\n'
on-the-fly like this:您可以像这样即时删除有问题的
$'\\n'
:
mapfile -t arr < <(tr -d '\r' <file.txt)
Other than that, I suggest you check you script with https://shellcheck.net/ as it has some issues除此之外,我建议你使用https://shellcheck.net/检查你的脚本,因为它有一些问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.