2014-09-05 72 views
1

好吧,这很可能听起来像是一个愚蠢的问题,但我无法让它工作,真的不知道我在这里做错了什么,即使在阅读后不少NAWK/awk的帮助网站:“nawk if else if else”不工作

$ echo -e "hey\nthis\nworld" | nawk '{ if ($1 !~ /e/) { print $0; } else if ($1 !~ /o/) { print $0; } else { print "condition not mached"; } }' 
    hey 
    this 
    world 
    $ 

我更愿意把它在同一行,但也试过上所看到的各种例子多行:

$ echo -e "hey\nthis\nworld" | nawk '{ 
    if ($1 !~ /e/) 
    print $0; 
    else if ($1 !~ /o/) 
    print $0; 
    else 
    print "condition not matched" 
    }' 
    hey 
    this 
    world 
    $ 

感谢您帮助一个nawk-新手!

我只是想只打印不包含特定图案的线,这里是“e”或“o”。 我只为测试目的添加了最后的其他部分。

回答

0

你可以简单地做让您的生活轻松了许多:

echo "hey\nthis\nworld" | nawk '$1 !~ /e|o/' 

什么,你的情况是怎么了?是:

$ echo -e "hey\nthis\nworld" | nawk '{ 
if ($1 !~ /e/) #'this' and 'world' satisfy this condition and so are printed 
print $0; 
else if ($1 !~ /o/) #Only 'hey' falls through to this test and passes and prints 
print $0; 
else 
print "condition not matched" 
}' 
hey 
this 
world 
$ 
+0

谢谢埃尔! 现在我看到了我在if结构中的误解。 – hermann 2014-09-05 14:18:38

0

FWIW做到这一点,正确的方法是用一个字符列表内三元表达式:

awk '{ print ($1 ~ /[eo]/ ? $0 : "condition not matched") }' 

如果您用标记您的问题,请继续前进而不是仅仅nawk(这是一个旧的,非POSIX和相对冗余的awk变体),它们将会覆盖更多的用户。