Anagram Checker Program in Bash

Anagram Checker Program in Bash

Introduction

This program demonstrates how to check if two strings are anagrams of each other in Bash. Two strings are considered anagrams if they contain the same characters in the same frequency, but in any order.

Bash Program


#!/bin/bash

# Function to check if two strings are anagrams
is_anagram() {
    str1="$1"
    str2="$2"
    
    # Sort the characters of both strings
    sorted_str1=$(echo "$str1" | grep -o . | sort | tr -d '\n')
    sorted_str2=$(echo "$str2" | grep -o . | sort | tr -d '\n')
    
    # Compare the sorted strings
    if [ "$sorted_str1" == "$sorted_str2" ]; then
        echo "The strings '$str1' and '$str2' are anagrams."
    else
        echo "The strings '$str1' and '$str2' are not anagrams."
    fi
}

# Main script execution
# Example strings
string1="listen"
string2="silent"

# Check if the strings are anagrams
is_anagram "$string1" "$string2"

    

Explanation

The program consists of a function is_anagram and the main script execution:

  • is_anagram: This function takes two strings as input parameters. It sorts the characters of each string and compares the sorted strings. If the sorted strings are equal, it prints that the strings are anagrams; otherwise, it prints that they are not.
  • Main script execution: The main part of the script defines two example strings, string1 and string2, and calls the is_anagram function to check if they are anagrams.

Key Points:

  • grep -o .: This command extracts each character of the string on a new line.
  • sort: This command sorts the characters alphabetically.
  • tr -d '\n': This command removes the newline characters to form a continuous string of sorted characters.
  • The comparison of the sorted strings determines if the original strings are anagrams.


By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)