脚本命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| file_list_1=("test1" "test2" "test3" "test4" "test5" "test6")
file_list_2=("test5" "test6" "test7" "test8")
# 获取并集,A ∪ B
file_list_union=(`echo ${file_list_1[*]} ${file_list_2[*]}|sed 's/ /\n/g'|sort|uniq`)
echo ${file_list_union[*]}
# 获取交集,A n B
file_list_inter=(`echo ${file_list_1[*]} ${file_list_2[*]}|sed 's/ /\n/g'|sort|uniq -c|awk '$1!=1{print $2}'`)
echo ${file_list_inter[*]}
# 对称差集,不属于 A n B
file_list_4=(`echo ${file_list_1[*]} ${file_list_2[*]}|sed 's/ /\n/g'|sort|uniq -c|awk '$1==1{print $2}'`)
echo ${file_list_4[*]}
|
命令解释
在上述三条命令中,首先使用echo 输出由两个数组构成的集合,然后使用sed将空格替换成换行符\n, 再使用sort排序:
- 使用
uniq处理则获得并集. - 使用
uniq -c处理则. 再使用awk分析第一个参数$1若不等于1就表示这是两个数组中,于是打印$2便得到交集. - 使用
uniq -c处理则. 再使用awk分析第一个参数$1若等于1就表示这是两个数组中,于是打印$2便得到差集.
命令参考
执行结果
1
2
3
| test1 test2 test3 test4 test5 test6 test7 test8
test5 test6
test1 test2 test3 test4 test7 test8
|