为了进行测试,我想计算一个目录中有多少个图像文件,并用文件扩展名(jpg =“ yes”来分隔每种图像文件类型。这是因为稍后它将对执行动作的另一个脚本很有用在每个文件扩展名上)。我可以仅对JPEG文件使用以下内容吗?
jpg=""
count=`ls -1 *.jpg 2>/dev/null | wc -l`
if [ $count != 0 ]
then
echo jpg files found: $count ; jpg="yes"
fi
考虑到文件扩展名jpg,png,bmp,raw和其他,我应该使用while
循环来做到这一点吗?
我建议采用另一种方法,以避免可能的单词拆分问题 ls
#!/bin/bash
shopt -s nullglob
for ext in jpg png gif; do
files=( *."$ext" )
printf 'number of %s files: %d\n' "$ext" "${#files[@]}"
# now we can loop over all the files having the current extension
for f in "${files[@]}"; do
# anything else you like with these files
:
done
done
您可以files
使用要在每个特定扩展名的文件上执行的任何其他命令来循环遍历该数组。
更便携-或对于没有显式提供数组的shell-您可以重用shell的位置参数数组,即
set -- *."$ext"
然后替换${#files[@]}
和${files[@]}
使用$#
,并"$@"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句