Some English words contain an "abba" structure, such as "tomorrow" or "better". How many lines of a given file contain such a word? How do i search such words using grep?

  • 3
    These seem like homework questions which you aren't really trying to research at all. Try consulting the man page of grep. – cutrightjm Nov 21 '15 at 1:38
  • Can you supply more language and linguistic information about the parameters of the search? I'm not exactly sure what you mean by "abba" structure and how it applies/relates/defines the attributes of "tomorrow" or "better". – RobertL Nov 21 '15 at 1:40

Try this with GNU grep:

grep '\(.\)\(.\)\2\1' file | wc -l
  • why do you specify GNU grep here? – mikeserv Nov 21 '15 at 8:04
  • @mikeserv: I tested it with GNU grep. – Cyrus Nov 21 '15 at 9:40
  • It is telling me there is no such file in directory. skhalid@cs:~/assignment3$ grep '(.)(.)\2\1' file | wc -l macbeth.html 5243 macbeth.html grep: file: No such file or directory – Usman Nov 21 '15 at 13:02
  • Replace "file" by your filename. – Cyrus Nov 21 '15 at 13:12

If you are looking for patterns that match palindromes - or words that are spelled the same way both forwards and backwards - you might open a GNU grep's info grep page and find...

Guglielmo Bondioni proposed a single RE that finds all palindromes up to 19 characters long using 9 subexpressions and 9 back-references:

grep -xE '(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?).?\9\8\7\6\5\4\3\2\1'

Note that this is done using GNU ERE extensions; it may not be portable to other implementations of grep.

...now that will match abba, but not tomorrow or better because neither of those words is a palindrome.

That note on portability, as I think, is specifically referring to the use of back-references in an Extended Regular Expression pattern - you'd need a lot more backslashes and a \{0,1\} to replace every question mark for a fully portable expression, I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.