【问题标题】:Convert bash line to use in perl将 bash 行转换为在 perl 中使用
【发布时间】:2014-06-14 13:18:42
【问题描述】:

我将如何将以下 bash 行转换为 perl?我可以运行 system() 命令,还是有更好的方法?我正在寻找 perl 从我的 apache access_log 文件中打印出每天的访问权限。

在 bash 中:

awk '{print $4}' /etc/httpd/logs/access_log | cut -d: -f1 | uniq -c

打印以下内容:

632 [27/Apr/2014
156 [28/Apr/2014

【问题讨论】:

  • 嘿,这不是真正的 Bash :D
  • +1 awk 是一种独立的语言。 gawk 是一个独立的程序。 cutuniq 是独立的命令;)

标签: apache perl bash awk


【解决方案1】:
awk '{print $4}' /etc/httpd/logs/access_log | cut -d: -f1 | uniq -c
perl -lane'
    ($val) = split /:/, $F[3];      # First colon-separated elem of the 4th field
    ++$c{$val};                     # Increment number of occurrences of val
    END { print for map { "$c{$_} $_" } keys %c }  # Print results in no order
' access.log

开关:

  • -l 自动将换行符附加到打印语句。
  • -l 还会从-n(和-p)读取的行中删除换行符。
  • -a 将空格上的行拆分为数组@F
  • -n 循环输入的行,但不打印每一行。
  • -e 执行给定的脚本体。

【讨论】:

    【解决方案2】:

    您的原始命令被翻译成 Perl 单行:

    perl -lane '($k) = $F[3] =~ /^(.*?):/; $h{$k}++ }{ print "$h{$_}\t$_" for keys %h' /etc/httpd/logs/access_log
    

    【讨论】:

    • @Virushunter,因为 Perl 从字面上用 LINE: while (<>) { ... } 包围了代码
    • @Virushunter }{THE END 块。您可以阅读有关特殊运算符的更多信息here
    • 酷,从来不知道这些......我想知道还有多少人在等待被追捕。谢谢你的链接
    【解决方案3】:

    您可以将所有命令更改为一个:

    awk '{print $4}' /etc/httpd/logs/access_log | cut -d: -f1 | uniq -c
    

    awk '{split($4,a,":");b[a[1]]++} END {for (i in b) print b[i],i}' /etc/httpd/logs/access_log
    

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      相关资源
      最近更新 更多