从一个数组中删除另一个数组中存在的项目?

时间:2020-01-18 10:02:20

标签: arrays bash

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

2 个答案:

答案 0 :(得分:0)

请尝试以下方法:

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的输出应该是反模式,我不建议使用后者。

答案 1 :(得分:0)

另一种变体

myfiles=( $(ls *.jpg) ) # add files to an array
myDownload=$(cat SiteFiles.txt) # add list to a var
# remove existing file from download list if exist
for item in "${myfiles[@]}"; { myDownload=${myDownload//$item/}; }
echo $myDownload