Find Palindrome using Grep command
All of you know that, grep is used to find out the text pattern in the file or from the output of any commands.
Now, we see how it will be used to find out the palidrome words.
We have to use the regular expression to find out the palindrome
Example :
1 2 3 4 5 6 7 8 9 10 11 | $ echo "madam" | grep -w '^\(.\)\(.\).\2\1' madam $ echo "radar" | grep -w '^\(.\)\(.\).\2\1' radar $ echo "test" | grep -w '^\(.\)\(.\).\2\1' $ $ echo "words" | grep -w '^\(.\)\(.\).\2\1' $ |
Explanation :
The grep command searches for the first any three letters by using \(.\)\(.\). after that we are searching the same 2nd character and 1st character is occuring or not.
The above grep command will find out only 5 letters palindrome words.
Guglielmo Bondioni proposed a single RE that finds all palindromes up to 19 characters long using 9 subexpressions and 9 back-references:
1 | grep -E -e '^(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?).?\9\8\7\6\5\4\3\2\1' file |
Notethis is done by using gnu ERE extensions; it might not be portable to other implementations ofgrep.
Recent Comments