我的目录包含许多子目录,每个子目录都有几个文件(仅对扩展名为 .ar 的文件感兴趣)。现在,我需要循环遍历每个子目录并检查,例如,如果文件数 = 4,则对这些文件执行某些操作,返回到第二个子目录检查文件,如果 = 3,则对它们执行另一个命令。请注意,我必须在 if 语句上应用非常复杂的条件。
与此类似的东西
dir=$1
for sub_dir in $dir; do
if the number of files in $sub_dir = 4; then
do something or command line
if the number of files in $sub_dir = 3; then
do another command
if the number of files in $sub_dir < 3; then
escape them
fi
done
我需要一个类似过程的模板。
答案1
假设子目录直接位于顶级目录下:
#!/bin/sh
topdir="$1"
for dir in "$topdir"/*/; do
set -- "$dir"/*.ar
if [ "$#" -eq 1 ] && [ ! -f "$1" ]; then
# do things when no files were found
# "$1" will be the pattern "$dir"/*.ar with * unexpanded
elif [ "$#" -lt 3 ]; then
# do things when less than 3 files were found
# the filenames are in "$@"
elif [ "$#" -eq 3 ]; then
# do things when 3 files were found
elif [ "$#" -eq 4 ]; then
# do things when 4 files were found
else
# do things when more than 4 files were found
fi
done
或者,使用case
:
#!/bin/sh
topdir="$1"
for dir in "$topdir"/*/; do
set -- "$dir"/*.ar
if [ "$#" -eq 1 ] && [ ! -f "$1" ]; then
# no files found
fi
case "$#" in
[12])
# less than 3 files found
;;
3)
# 3 files found
;;
4)
# 4 files found
;;
*)
# more than 4 files found
esac
done
需要文件名的代码分支用于"$@"
引用子目录中的所有文件名,或者"$1"
等等"$2"
来引用各个文件。文件名将是包括$topdir
开头目录的路径名。
答案2
你可以这样做:
dir=$1
subdirectories = $(find $dir -type d) # find only subdirectories in dir
for subdir in $subdirectories
do
n_files=$(find $subdir -maxdepth 1 -type f | wc -l) # find ordinary files in subdir and get it quantity
if [ $n_files -eq 4 ]
then
do_something_4
fi
if [ $n_files -eq 3 ]
then
do_something_3
fi
if [ $n_files -lt 3 ]
then
do_something_else
fi
done