2014-11-24 42 views
1

我將一些命令的輸出傳送給perl。輸出由一組文件名和目錄組成,我希望perl過濾掉那些目錄。這樣的事情:Perl'-d'操作符未檢測到目錄

...some commands... | perl -ne 'print $_ unless -d($_);' 

事情是,它不是過濾目錄!例如,輸出是一樣的東西:

test/unit_test/ipc 
test/unit_test/ipc/tc1.cpp 

test/unit_test/ipc是一個目錄,但它仍然是輸出。

回答

4

由perl one-liner 讀入的$_的值包括尾隨換行符。因此,-d甚至找不到該目錄,更不用說認識到它是一個目錄。

這裏是一個解決方案:

...some commands... | perl -ne 'chomp $_; print "$_\n" unless -d $_ ;' 

使用注意事項的chomp刪除尾隨換行符。


在結合-n-p-l不僅增加了一個新行到print編字符串,它chomp S上的輸入。這意味着你的代碼可以簡化爲

...some commands... | perl -nle 'print $_ unless -d $_;' 

甚至

...some commands... | perl -nle'print if !-d' 
+1

在這種情況下,-d將返回民主基金,而不是虛假的或真實的,那麼你就可以知道$檢查!對於錯誤消息 – ysth 2014-11-24 01:14:40

+0

也許有用點 - 默認情況下'chomp'作用於$ _。 – Sobrique 2014-11-24 10:05:04