BASH 回文检查器 [英] BASH Palindrome Checker
问题描述
这是我第一次在这里发帖,请多多包涵.
This is my first time posting on here so bear with me please.
我收到了一份 bash 作业,但我的教授完全没有帮助,他的笔记也是如此.
I received a bash assignment but my professor is completely unhelpful and so are his notes.
我们的任务是从文件中过滤并打印出回文.在本例中,目录为:
Our assignment is to filter and print out palindromes from a file. In this case, the directory is:
/usr/share/dict/words
字长范围从3到45,应该只过滤小写字母(给出的字典有字符和大写字母,也有小写字母).即-dkas-das"所以像q-evvavve-q"这样的东西可能算作回文,但我不应该将其视为正确的结果.
The word lengths range from 3 to 45 and are supposed to only filter lowercase letters (the dictionary given has characters and uppercases, as well as lowercase letters). i.e. "-dkas-das" so something like "q-evvavve-q" may count as a palindrome but i shouldn't be getting that as a proper result.
无论如何,我可以让它过滤掉 x 个单词并返回(虽然不只过滤小写字母).
Anyways, I can get it to filter out x amount of words and return (not filtering only lowercase though).
grep "^...$" /usr/share/dict/words |
grep "(.).1"
我可以使用后续行表示 5 个字母的单词和 7 个等等:
And I can use subsequent lines for 5 letter words and 7 and so on:
grep "^.....$" /usr/share/dict/words |
grep "(.)(.).21"
但是教授不希望那样.我们应该使用循环.我明白了这个概念,但我不知道语法,就像我说的那样,注释非常无用.
But the prof does not want that. We are supposed to use a loop. I get the concept but I don't know the syntax, and like I said, the notes are very unhelpful.
我尝试的是设置变量 x=... 和 y=.. 并在 while 循环中设置 x=$x$y 但这不起作用(语法错误),x+=..
What I tried was setting variables x=... and y=.. and in a while loop, having x=$x$y but that didn't work (syntax error) and neither did x+=..
感谢任何帮助.甚至过滤掉我的非小写字母.
Any help is appreciated. Even getting my non-lowercase letters filtered out.
谢谢!
如果您要提供解决方案或解决方案的提示,则首选最简单的方法.最好使用 2 个 grep 语句和一个循环.
If you're providing a solution or a hint to a solution, the simplest method is prefered. Preferably one that uses 2 grep statements and a loop.
再次感谢.
推荐答案
像这样:
for word in `grep -E '^[a-z]{3,45}$' /usr/share/dict/words`;
do [ $word == `echo $word | rev` ] && echo $word;
done;
使用我的字典输出:
aha
bib
bob
boob
...
wow
更新
正如评论中所指出的,在 for 循环中将大部分字典读入变量可能不是最有效的,并且有在某些 shell 中触发错误的风险.这是一个更新的版本:
As pointed out in the comments, reading in most of the dictionary into a variable in the for loop might not be the most efficient, and risks triggering errors in some shells. Here's an updated version:
grep -E '^[a-z]{3,45}$' /usr/share/dict/words | while read -r word;
do [ $word == `echo $word | rev` ] && echo $word;
done;
这篇关于BASH 回文检查器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!