The command "rev" reverses the lines of the file given to it as input. we can use this command to find out whether a given string is palindrome or no.
A palindrome is any string that appears the same when read from left to right or right to left.
For Eg:
mom : will be same if we read it left to right or right to left, hence it is a palindrome.
tree: will be read as eert if read from right to left which is different from tree hence the string is not a palindrome.
The command rev takes the lines of file given as input and prints them in reverse.
For eg:
If we have a file named "one" with contents "The weather has been cloudy "
$ rev one
yduolc neeb sah rehtaew ehT
A palindrome is any string that appears the same when read from left to right or right to left.
For Eg:
mom : will be same if we read it left to right or right to left, hence it is a palindrome.
tree: will be read as eert if read from right to left which is different from tree hence the string is not a palindrome.
The command rev takes the lines of file given as input and prints them in reverse.
For eg:
If we have a file named "one" with contents "The weather has been cloudy "
$ rev one
yduolc neeb sah rehtaew ehT
As we see rev prints the line from right to left.
Now let us try to write a script that will use "rev" to find out if a given string is a palindrome or not.
Note: The script creates and new file by the name temp in the present working directory and deletes it . In case you have any other file by the name temp, it will get overwritten and deleted if you do not rename it or modify the script.
#! /bin/bash
if [ $# -le 2 ] # if word is not passed in command line, take it as input.
then
echo "Enter the word"
read input # Store the word in variable input
fi
echo $input > temp # Write the input into a temporary file.
reverse=`rev temp` # Run the command rev on the temporary file . store result in another variable
echo $reverse
if [ $input==$reverse ] #Compare the input and reversed string.
then
echo "it is a palindrome"
else
echo "Not a palindrome"
fi
rm temp # Remove the temporary file created.
No comments:
Post a Comment