unix - shell - Characters contained in both strings - edited -
i want compare 2 string variables , print characters same both. i'm not sure how this, thinking of using comm or diff i'm not sure right parameters print matching characters. take in files , these strings. can help?
input:
a=$(echo "abghrsy") b=$(echo "cgmnorstuvz") output:
"grs"
use character classes gnu grep
the isn't widely-applicable solution, fits particular use case quite well. idea use first variable character class match against second string. example:
a='abghrsy' b='cgmnorstuvz' echo "$b" | grep --only-matching "[$a]" | xargs | tr --delete ' ' this produces grs expect. note use of xargs , tr remove newlines , spaces output; can handle other way if prefer.
set intersection
what you're looking set intersection, though. while can "wing it" in shell, you'd better off using language ruby, python, or perl this.
a ruby one-liner
if need integrate existing shell script, simple ruby one-liner uses bash variables called inside current script:
a='abghrsy' b='cgmnorstuvz' ruby -e "puts ('$a'.split(//) & '$b'.split(//)).join" a ruby script
you make things more elegant doing whole thing in ruby instead.
string1_chars = 'abghrsy'.split // string2_chars = 'cgmnorstuvz'.split // intersection = string1_chars & string2_chars puts intersection.join this seems more readable , robust me, mileage may vary. @ least have options choose from.
Comments
Post a Comment