当我将 NOT 与 AND 和 OR 一起使用时,我无法真正理解 BOOLEAN 逻辑
我试图理解当我使用 NOT 时布尔逻辑是如何工作的。举一个使用 awk 的例子,
我有一个文本文件,其中包含
CORE
PORT
CORE
PORT
COREPORT
CORE
COREPORT
And I Walk 删除所有 COREPORT 行。我认为我会这样做的方式是使用(不是核心)和(不是端口)例如
awk '/!CORE/&&/!PORT/{print}'
但是当我尝试它时我实际上应该使用 OR 而不是 AND
awk '/!CORE/||/!PORT/{print}'
如果有人可以解释我的想法在哪里是错误的,我会很高兴如果可以用维恩图或布尔机之类的东西将其可视化,我非常高兴 kathyschrock
Im trying to understand how boolean logic works when I use NOT. To give an example using awk
I have a text file containing
CORE
PORT
CORE
PORT
COREPORT
CORE
COREPORT
And I would like to remove all COREPORT lines. The way I thought I would do it was with (NOT CORE) AND (NOT PORT) eg
awk '/!CORE/&&/!PORT/{print}'
But when I try it out Im actually supposed to use OR instead of AND
awk '/!CORE/||/!PORT/{print}'
I would be really glad if some one could explain where my thinking is wrong and super glad if it could be visualized with a venn diagram or something like the boolean machine at kathyschrock
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会尝试给出一种直觉或你的布尔表达式,对于数学,其他海报做得很好。
对于您想要保留的行,您的布尔表达式必须为真。
因此,您的布尔表达式表示保留同时不包含 PORT 和不包含 CORE 的行。显然你的文件中没有这样的行...
你必须使用
or
因为你真正想要表达的是保留不包含 PORT 和 CORE 的行,但正如你所看到的上述陈述中只有一个否定。你试图说这样的话:线是否包含 PORT,它是否也包含 CORE 那么我不想要它。这就是!(/CORE/ && /PORT/)
,使用布尔数学你也可以写成/!CORE/||/!PORT/
正如您亲眼所见。一般来说,负面断言很难理解。我不是唯一这么说的人。例如,Damian Conway 在 Perl Best Practice 中指出了这一点,并建议尽可能使用肯定语句(并在以下情况下使用
unless
Perl 运算符而不是if
你想否定一个条件)。I will try to give a gut feeling or your boolean expressions, for maths other posters did it very well.
Your boolean expression must be true for the lines you want to keep.
Hence your boolean expression means keep the lines that as the same time does not contains PORT and does not contains CORE. Obviously there is no such lines in your file...
You must use
or
because what you truly want to express is keep the lines that does not contain both PORT and CORE, but as you can see there is only one negation in the above statement. You are trying to say something like: does line contain PORT, does it also contains CORE then I do not want it. And that is!(/CORE/ && /PORT/)
, and using boolean math you can also write that/!CORE/||/!PORT/
as you have seen by yourself.Generally speaking negative assertions are difficult to understand. I'm not the only one to say that. For example, Damian Conway in Perl Best Practice pointed it out and recommanded using positive statements whenever possible (and use
unless
Perl operator instead ofif
when you want to negate a condition).你为什么不这样做
why don't you do it this way
真相表即将推出...
Truth Table coming up...
可视化逻辑的一个好方法是卡诺图。
或者,如果您想处理数学表达式,请记住:
实际上,你想要的不是:(not CORE) and (not PORT) 但是:不是(CORE 和 PORT),这与:(不是 CORE)或(不是 PORT)
A good way for visualising logic is Karnaugh map.
Or, if you want to handle math expressions, just remember that:
Actually, what you want is not: (not CORE) and (not PORT) but: not (CORE and PORT) which is the same as: (not CORE) or (not PORT)