Anagram Checker Program in Bash






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.


Leave a Reply

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