【问题标题】:How to retain file name using Perl replacement for grep如何使用 Perl 替换 grep 保留文件名
【发布时间】:2010-11-23 03:57:54
【问题描述】:

考虑以下使用 grep 的命令行输出:

[gjempty@gjempty]$ 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 的命令行替代品?

[gjempty@gjempty]$ 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();

【问题讨论】:

    标签: perl command-line grep


    【解决方案1】:

    您可以尝试将$ARGV 用作:

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

    【讨论】:

      【解决方案2】:

      在 Perl 中构建更好的 grep 版本已经完成;它叫做ack

      ack --type=php __construct
      

      或者,如果您想要每个匹配行的文件名(而不是作为标题):

      ack --type=php --nogroup __construct
      

      请注意,您也不需要 find ... | xargs ... 部分。 --type=php 参数代替了查找。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-29
        • 2018-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-14
        相关资源
        最近更新 更多