Now that I understand what you mean by "array", I think -- first of all -- that you should consider using actual Bash arrays. They're much more flexible, in that (for example) array elements can contain whitespace, and you can avoid the risk that *
and ?
will trigger filename expansion.
But if you prefer to use your existing approach of whitespace-delimited strings, then I agree with RHT's suggestion to use Perl:
result=$(perl -e 'my %array2 = map +($_ => 1), split /\s+/, $ARGV[1];
print join " ", grep $array2{$_}, split /\s+/, $ARGV[0]
' "$array1" "$array2")
(The line-breaks are just for readability; you can get rid of them if you want.)
In the above Bash command, the embedded Perl program creates a hash named %array2
containing the elements of the second array, and then it prints any elements of the first array that exist in %array2
.
This will behave slightly differently from your code in how it handles duplicate values in the second array; in your code, if array1
contains x
twice and array2
contains x
three times, then result
will contain x
six times, whereas in my code, result
will contain x
only twice. I don't know if that matters, since I don't know your exact requirements.