BASH回文检查 [英] BASH Palindrome Checker

查看:159
本文介绍了BASH回文检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次张贴在这里如此忍受我请。

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,并且应该仅过滤小写字母(给定字典有字符和uppercases,以及小写字母)。即-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 "\(.\)\(.\).\2\1" 

但教授不希望出现这种情况。我们应该使用一个循环。我得到的概念,但我不知道语法,就像我说的,票据是非常无益的。

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 = ..并在循环,有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+=..

任何帮助是AP preciated。甚至还让我的非小写字母过滤掉了。

Any help is appreciated. Even getting my non-lowercase letters filtered out.

谢谢!

如果你提供了一个解决方案或暗示的解决方案,最简单的方法是prefered。
preferably一个使用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;

输出使用我的字典:

Output using my dictionary:

aha
bib
bob
boob
...
wow

更新

由于在评论中指出,阅读在大多数的字典到一个变量在for循环可能不是最有效的,与风险引发了一些炮弹的错误。下面是一个更新版本:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆