Compare/Difference of two arrays in bash -


is possible take difference of 2 arrays in bash.
great if suggest me way it.

code :

array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" ) array2=( "key1" "key2" "key3" "key4" "key5" "key6" )   array3 =diff(array1, array2)  array3 ideally should : array3=( "key7" "key8" "key9" "key10" ) 

appreciate help.

if strictly want array1 - array2, then

 $ array3=() $ in "${array1[@]}"; >     skip= >     j in "${array2[@]}"; >         [[ $i == $j ]] && { skip=1; break; } >     done >     [[ -n $skip ]] || array3+=("$i") > done $ declare -p array3 

runtime might improved associative arrays, wouldn't bother. if you're manipulating enough data matter, shell wrong tool.


for symmetric difference dennis's answer, existing tools comm work, long massage input , output bit (since work on line-based files, not shell variables).

here, tell shell use newlines join array single string, , discard tabs when reading lines comm array.

 $ oldifs=$ifs ifs=$'\n\t' $ array3=($(comm -3 <(echo "${array1[*]}") <(echo "${array2[*]}"))) comm: file 1 not in sorted order $ ifs=$oldifs $ declare -p array3 declare -a array3='([0]="key7" [1]="key8" [2]="key9" [3]="key10")' 

it complains because, lexographical sorting, key1 < … < key9 > key10. since both input arrays sorted similarly, it's fine ignore warning. can use --nocheck-order rid of warning, or add | sort -u inside <(…) process substitution if can't guarantee order&uniqueness of input arrays.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -