Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if two strings of any length are anagrams using bash, awk or any using command or script?

Tags:

bash

sed

awk

The string or word can be of any length.

Eg "William Shakespeare" = "I am a weakish speller" both are anagrams

E.g. "Madam Curie" = "Radium came"

like image 529
Vicky Avatar asked Dec 13 '25 05:12

Vicky


1 Answers

This may work for you:

# function to cleanup a given argument by doing this:
# 1. Remove all alphanumerics
# 2. Convert to all lowercasing all characters 
# 3. Sorting all characters
# 4. Stripping all newlines 
prep() {
   fold -w1 <<< "${1//[^[:alnum:]]/}" | tr '[:upper:]' '[:lower:]' | sort | tr -d '\n'
}

# function to check if given 2 arguments are anagrams
isAnagram() {
   a=$(prep "$1")
   b=$(prep "$2")
   [[ $a = $b ]] && echo "yes" || echo "no";
}

To call them use:

isAnagram "William Shakespeare" "I am a weakish speller"
yes

isAnagram "Madam Curie" "Radium came"
yes

isAnagram "cat" "act"
yes

isAnagram "cat" "cot"
no
like image 182
anubhava Avatar answered Dec 14 '25 18:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!