Bit*_*ker 7 command-line bash directory find shell-script
+--- Root_Dir
| +--- Dir_A
| | +--- abc.txt
| | +--- 123.txt
| | +--- .hiddenfile
| | +--- .hidden_dir
| | | +--- normal_sub_file_1.txt
| | | +--- .hidden_sub_file_1.txt
| |
| +--- Dir_B
| | +--- abc.txt
| | +--- .hidden_dir
| | | +--- normal_sub_file_2.txt
| | | +--- .hidden_sub_file_2.txt
| |
| +--- Dir_C
| | +--- 123.txt
| | +--- program.c
| | +--- a.out
| | +--- .hiddenfile
| |
| +--- Dir_D
| | +--- .hiddenfile
| | +--- .another_hiddenfile
| |
| +--- Dir_E
| | +--- .hiddenfile
| | +--- .hidden_dir
| | | +--- normal_sub_file_3.txt # This is OK because its within a hidden directory, aka won't be checked
| | | +--- .hidden_sub_file_3.txt
| |
| +--- Dir_F
| | +--- .hidden_dir
| | | +--- normal_sub_file_4.txt
| | | +--- .hidden_sub_file_4.txt
Run Code Online (Sandbox Code Playgroud)
./Root_Dir/Dir_D
./Root_Dir/Dir_E
./Root_Dir/Dir_F
Run Code Online (Sandbox Code Playgroud)
Dir_D因为它只包含隐藏文件。Dir_E因为它只包含我正在搜索的级别的隐藏文件和隐藏目录。Dir_F因为它只包含我正在搜索的级别的隐藏目录。find命令来获取我正在寻找的结果,但我似乎无法弄清楚我需要将输出传输到哪个其他命令或我应该使用哪些其他选项。bob@linux:/$ find ./Root_Dir -mindepth 2 -maxdepth 2 -type d -name "*." -type -f -name "*." | command to see if these are the only files in that directory
Run Code Online (Sandbox Code Playgroud)
我对此有一个不太漂亮的解决方案。
以脚本形式:
#!/bin/bash
# Echo whatever is passed to fail, and then exit with a status of 1
fail() {
echo >&2 "$@"
exit 1
}
# If the number of arguments are less or more than what
# we expect, throw help syntax and exit.
if [ $# -gt 2 ] || [ $# -lt 2 ]
then
fail "
$0 check for directories that only contain hidden listings
Usage: $0 <Directory to search from> <Depth to check>
"
fi
# Assign parameters
root_dir=$1
depth=$2
# Find a list of directories that contain files OR subdirectories
# that are hidden
readarray -t dirs < <(export LC_ALL=C
find "$root_dir" -mindepth "$depth" -maxdepth "$depth" \
-name ".*" \( -type d -o -type f \) -execdir pwd \; | sort -u
)
# Of the dirs we found, do any of them return any listings with a
# default ls execution? If so, that directory cannot only contain
# hidden listings.
final=()
for dir in "${dirs[@]}"
do
notExclusive="$(ls -- "$dir")"
if [ "$notExclusive" = "" ]
then
final+=("$dir")
fi
done
# The array final contains the directories who only contain hidden
# files/subdirectories.
printf '%s\n' "${final[@]}"
Run Code Online (Sandbox Code Playgroud)
基本上,我们只是找到包含隐藏列表的目录(按问题指定的深度为 2),将它们加载到数组中,如果ls没有标志返回任何内容,我们可以得出结论,该目录中只包含隐藏列表,满足我们的标准。
解释一下为什么你只需要find根据 OP 上的评论调用一次。该命令find具有用于基本逻辑的运算符,-a 是连接两个表达式逻辑 AND 时的默认行为,! 如逻辑“非”,-o 如逻辑“或”。
此方法假设目录路径不包含换行符,如果包含换行符,则会readarray错误地分隔每个目录路径。
丑陋的“一行”:
readarray -t dirs < <(export LC_ALL=C; find ./Root_Dir -mindepth 2 -maxdepth 2 -name '.*' \( -type d -o -type f \) -execdir pwd \; | sort -u); final=(); for dir in "${dirs[@]}"; do notExclusive="$(ls -- "$dir")"; if [ "$notExclusive" = "" ]; then final+=("$dir"); fi; done; printf '%s\n' "${final[@]}"
Run Code Online (Sandbox Code Playgroud)