我想删除出现在 中的所有单词,VAR1
也出现在 中VAR2
。
例如:
VAR1=a2,a3,a4,a5,a6,a1
VAR2=a1,a2,a6,a4,a7,a8
我想要的结果是:
VAR1=a3,a5
VAR2=a7,a8
答案1
在 中zsh
,您可以使用其数组减法运算符:
$ VAR1=a2,a3,a4,a5,a6,a1
$ VAR2=a1,a2,a6,a4,a7,a8
$ array1=(${(s:,:)VAR1})
$ array2=(${(s:,:)VAR2})
$ echo ${(j:,:)array1:|array2}
a3,a5
$ echo ${(j:,:)array2:|array1}
a7,a8
答案2
扩展tr
+sort
+paste
+comm
解决方案:
VAR1="a2,a3,a4,a5,a6,a1"
VAR2="a1,a2,a6,a4,a7,a8"
temp1="$VAR1"
temp2="$VAR2"
VAR1=$(comm -23 <(tr ',' '\n' <<<"$temp1" | sort) <(tr ',' '\n' <<<"$temp2" | sort) | paste -d',' -s)
VAR2=$(comm -13 <(tr ',' '\n' <<<"$temp1" | sort) <(tr ',' '\n' <<<"$temp2" | sort) | paste -d',' -s)
结果:
$ echo "$VAR1"
a3,a5
$ echo "$VAR2"
a7,a8
答案3
在下面的脚本中,我已指定 tmp1=$VAR1 和 tmp2=$VAR2 作为临时变量。
下面的awk
一个衬垫脚本经过测试,效果很好
tmp1=$VAR1;tmp2=$VAR2
VAR1=$(awk 'NR==FNR {a[$1];next}!($1 in a) {print $1}' <(echo $tmp2|perl -pne "s/,/\n/g") <(echo $tmp1|perl -pne "s/,/\n/g")|perl -pne "s/\n/,/g"| sed "s/,$//g")
VAR2=$(awk 'NR==FNR {a[$1];next}!($1 in a) {print $1}' <(echo $tmp1|perl -pne "s/,/\n/g") <(echo $tmp2|perl -pne "s/,/\n/g")|perl -pne "s/\n/,/g"| sed "s/,$//g")
输出
echo $VAR1
a3,a5
echo $VAR2
a7,a8
答案4
与 Jeff 的答案类似的方法,但使用 perl
source <(
perl -se '
@v1 = split /,/, $v1;
@v2 = split /,/, $v2;
@h1{@v1} = (1) x @v1; delete @h1{@v2};
@h2{@v2} = (1) x @v2; delete @h2{@v1};
printf qq{VAR1only="%s"\n}, join ",", keys %h1;
printf qq{VAR2only="%s"\n}, join ",", keys %h2;
' -- -v1="$VAR1" -v2="$VAR2"
)
echo "$VAR1only -- $VAR2only"
a3,a5 -- a7,a8