2010-11-22 37 views
2

用grep考慮以下命令行輸出:如何使用Perl替代grep來保留文件名

[[email protected]]$ find . -name "*.php" | xargs grep __construct | tail 
./ilserverd/src/php/ImageLoopIntegrationService.php: public function __construct($input, $output=null) { 
./ilserverd/src/php/ImageLoopIntegrationService.php: public function __construct($vals=null) { 
./ilserverd/src/php/ImageLoopIntegrationService.php: public function __construct($vals=null) { 
./ilserverd/src/php/ImageLoopIntegrationService.php: public function __construct($vals=null) { 
./ilserverd/src/php/ImageLoopIntegrationService.php: public function __construct($vals=null) { 
./ilserverd/src/php/ImageLoopIntegrationService.php: public function __construct($handler) { 
./ilserverd/src/php/il_server_types.php: public function __construct($vals=null) { 
./ilserverd/src/php/il_server_types.php: public function __construct($vals=null) { 
./utilities/studio/legacy/full_bleed_update_photobook_themes.php: public function __construct() { 
./utilities/studio/legacy/full_bleed_update_photobook_themes.php:  parent::__construct(); 

這是我在試圖提取構造函數的參數第一步,因爲它需要許多步驟,我試圖用Perl作爲對grep的改進。但首先,我想保留文件名,以便我可以參考最後的「報告」輸出中的那些文件名。

但是,當我切換到下面的Perl單行文件名不再是輸出的一部分。我怎樣才能保留它們並仍然使用Perl作爲命令行替換grep?

[[email protected]]$ find . -name "*.php" | xargs perl -wnl -e '/__construct/ and print' | tail 
    public function __construct($input, $output=null) { 
    public function __construct($vals=null) { 
    public function __construct($vals=null) { 
    public function __construct($vals=null) { 
    public function __construct($vals=null) { 
    public function __construct($handler) { 
    public function __construct($vals=null) { 
    public function __construct($vals=null) { 
    public function __construct() { 
     parent::__construct(); 

回答

5

您可以嘗試使用$ARGV爲:

perl -wnl -e '/__construct/ and print "$ARGV: $_"' 
+2

http://search.cpan.org/perldoc?perlvar#ARGV – mob 2010-11-22 18:59:17

3

構建一個更好的版本在Perl的grep已經完成;它被稱爲ack

ack --type=php __construct 

或者,如果你想與每個匹配行的文件名(而不是作爲一個標題):

ack --type=php --nogroup __construct 

請注意,您不需要find ... | xargs ...部分,無論是。參數代替了查找。