2014-09-05 71 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變體),它們將會覆蓋更多的用戶。