Check if Two Strings are Anagrams – Bash Script
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. This Bash script will check if two given strings are anagrams of each other.
Program Structure
The script follows these steps:
- Read two input strings.
- Remove any whitespace and convert the strings to lowercase for uniformity.
- Sort the characters of both strings.
- Compare the sorted strings.
- Print whether the strings are anagrams or not based on the comparison.
Script Documentation
#!/bin/bash
# Function to sort characters of a string
sort_string() {
echo "$1" | sed 's/ //g' | fold -w1 | sort | tr -d '\n'
}
# Main program
echo "Enter the first string:"
read string1
echo "Enter the second string:"
read string2
# Remove spaces and convert to lowercase
string1=$(echo "$string1" | tr -d ' ' | tr '[:upper:]' '[:lower:]')
string2=$(echo "$string2" | tr -d ' ' | tr '[:upper:]' '[:lower:]')
# Sort and compare
sorted_string1=$(sort_string "$string1")
sorted_string2=$(sort_string "$string2")
if [ "$sorted_string1" == "$sorted_string2" ]; then
echo "The strings are anagrams."
else
echo "The strings are not anagrams."
fi
Explanation:
- Function
sort_string
:- Removes spaces from the input string.
- Breaks it into individual characters.
- Sorts the characters alphabetically.
- Joins them back into a single string.
- Main Program:
- Reads two strings from the user.
- Removes spaces and converts to lowercase to handle case-insensitivity and ignore whitespace.
- Uses the
sort_string
function to sort the characters of both strings. - Compares the sorted strings to determine if they are anagrams.
- Outputs the result.
The script performs the following tasks:
- Function sort_string: This function takes a string as input, removes spaces, splits it into individual characters, sorts them, and then joins them back together.
- Reading Input: The script reads two strings from the user.
- Normalization: It removes any whitespace and converts both strings to lowercase to ensure the comparison is case-insensitive and whitespace is ignored.
- Sorting and Comparison: Both strings are sorted using the sort_string function. The sorted versions are compared to check if they are identical.
- Output: The script prints whether the two strings are anagrams based on the comparison.