我有一个数组:
src_dir=( /etc /var/www /var /var/html /home/user)
我想要这样的输出:
/etc
/var contains /var/www /var/html
/home/user
到目前为止,我已经尝试过:
src_dir=( /etc /var/www /var /var/html /home/user)
declare exclude
for src in ${src_dir[@]}; do
if ! [[ " $src " =~ $exclude ]]; then
exclude+=("$src")
fi
done
答案 0 :(得分:1)
尝试使用此Shellcheck干净的代码:
#! /bin/bash -p
src_dir=( /etc /var/www /var /var/html /home/user)
for src in "${src_dir[@]}"; do
# Determine if $src contains other elements ($is_container), and which
# elements contain it ($containers)
is_container=0
containers=() # Elements that this element is part of
for src2 in "${src_dir[@]}"; do
if [[ $src2 == "$src" ]] ; then
# Don't count an element as being part of itself
continue
elif [[ $src == *"$src2"* ]]; then
is_container=1
break
elif [[ $src2 == *"$src"* ]] ; then
containers+=( "$src2" )
fi
done
# Skip elements that contain other elements.
# Print elements elements that don't contain other elements, and any
# elements that contain them.
if (( is_container )) ; then
continue
elif (( ${#containers[*]} > 0 )) ; then
printf '%s is contained in' "$src"
printf ' %q' "${containers[@]}"
printf '\n'
else
printf '%s\n' "$src"
fi
done
=~
)在Bash中有一些奇怪之处,最好避免。在这里使用[[ ... == ... ]]
进行简单的模式匹配就足够了。(/home /home/user /home/user/dir)
,则/home/user
不会被列为包含在/home/user/dir
中。那可能不是您想要的。/home/user
被认为包含在/home/user2
中。那可能不是您想要的。/home
和/user
都将被列为包含在/home/user
中。那可能不是您想要的。