Search code examples
bashawksed

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


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"


Solution

  • 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