首页 > 解决方案 > 从一个数组中删除另一个数组中存在的项目?

问题描述

我正在下载一个文件列表,但是我想优化它,如果它已经下载,它就不会去下载。我想过用myfiles=$(ls *.jpg);创建一个数组 然后从我的文件列表中排除这些文件myDownload=$(cat SiteFiles.txt)。最终需要从myDownload中删除myfiles中的项目。我想知道这是否可能,是否可能存在不够聪明等问题。例如 [ abcd ] 在像 [ 1 a 2 b 3 c 4 d ] 这样的辅助数组上找不到 b ,因为数组不匹配顺序。

标签: arraysbash

解决方案


你会尝试以下方法:

declare -A ihaveit      # create an associative array
for f in *.jpg; do
    (( ihaveit[$f]++ )) # set a mark for files at hand
done

while read -r f; do
    [[ -z ${ihaveit[$f]} ]] && myDownload+=("$f")
                        # if the file in the SiteFiles.txt is not in my list
                        # then append it to the download list
done < SiteFiles.txt

echo "${myDownload[@]}" # see the result

如果您更喜欢单行且文件名不包含换行符,您也可以这样说:

comm -2 -3 <(sort SiteFiles.txt) <(ls -1 *.jpg | sort)

请注意,解析的输出ls通常应该是一种反模式,我不建议使用后者。


推荐阅读