arrays - 从一个数组中删除另一个数组中存在的项目?
问题描述
我正在下载一个文件列表,但是我想优化它,如果它已经下载,它就不会去下载。我想过用myfiles=$(ls *.jpg)
;创建一个数组 然后从我的文件列表中排除这些文件myDownload=$(cat SiteFiles.txt)
。最终需要从myDownload中删除myfiles中的项目。我想知道这是否可能,是否可能存在不够聪明等问题。例如 [ abcd ] 在像 [ 1 a 2 b 3 c 4 d ] 这样的辅助数组上找不到 b ,因为数组不匹配顺序。
解决方案
你会尝试以下方法:
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
通常应该是一种反模式,我不建议使用后者。
推荐阅读
- angular - 多次单击时未选中角度材料垫单选按钮
- haskell - 如果在不同的模块中使用相同的名称,haskell 会隐藏类型吗?
- java - 在另一个屏幕元素上设置 ARCore Sceneview
- javascript - 在为它们动态创建持有者后渲染图表不起作用
- python - 如果我使用感叹号,为什么我会在 yaml 文件的输出中得到引号?
- python-3.x - 列表中元素的幂
- winforms - ms access - like 关键字在 winform 中不起作用
- adal - adalAuthenticationService.getUser() 在 adal-angular 包装器中不起作用
- python - 无法在 Fedora 上安装 QISKIT
- android - Mysql,Android Retrofit:尝试在空对象引用上调用接口方法