【问题标题】:Grep from within perl script来自 perl 脚本的 Grep
【发布时间】:2015-07-16 19:53:37
【问题描述】:

关于如何在 perl 脚本中声明 grep,我有点陷入困境。我想要做的是让我的 perl 脚本执行以下命令:

cat config.ini | grep -v "^#" | grep -v "^$"

通常这个表达式会清理/过滤所有以#和$开头的条目并打印配置的变量。

但是我不知道如何声明它。我已经使用了下一个表达式,但是当我要引入 grep # 或 $ 时它失败了

system("(cat config.ini| grep ........);

有什么建议吗?

【问题讨论】:

  • /^[#$]/ or print while <$fh>;perl -ne '/^[#$]/ or print' config.ini

标签: regex linux perl perlscript


【解决方案1】:
cat config.ini | grep -v "^#" | grep -v "^$"

是一种糟糕的写作方式

grep -v "^[#$]" config.ini

生成字符串

grep -v "^[#$]" config.ini

你可以使用字符串字面量

'grep -v "^[#$]" config.ini'

所以

system('grep -v "^[#$]" config.ini');
die("Killed by signal ".($? & 0x7F)."\n") if $? & 0x7F;
die("Exited with error ".($? >> 8)."\n") if $? >> 8;

system('grep -v "^[#$]" config.ini');

简称

system('/bin/sh', '-c', 'grep -v "^[#$]" config.ini');

但是我们不需要shell,所以可以用下面的代替:

system('grep', '-v', '^[#$]', 'config.ini');
die("Killed by signal ".($? & 0x7F)."\n") if $? & 0x7F;
die("Exited with error ".($? >> 8)."\n") if $? >> 8;

但是在 Perl 中做会更干净、更健壮。

open(my $fh, '<', 'config.ini')
   or die($!);

while (<$fh>) {
   print if !/^[#$]/;
}

【讨论】:

    【解决方案2】:

    如果您从 Perl 程序内部对 grep 进行外部调用,那么您做错了。 grep 没有什么是 Perl 不能为你做的。

    while (<$input_filehandle>) {
      next if /^[#$]/; # Skip comment lines or empty lines.
    
      # Do something with your data, which is in $_
    }
    

    更新:进一步考虑这一点,我想我会写得稍微不同。

    while (<$input_filehandle>) {
      # Split on comment character - this allows comments to start
      # anywhere on the line.
      my ($line, $comment) = split /#/, $_, 2;
    
      # Check for non-whitespace characters in the remaining input.
      next unless $line =~ /\S/;
    
      # Do something with your data, which is in $_
    }
    

    【讨论】:

      【解决方案3】:
      print if !(/^#/|/^$/);
      

      我确实尝试使用建议的表达式,但效果不如这个,有没有办法减少它或以更好的方式编写 ir?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多