perl - 难以将 Perl 脚本作为 Bash 别名运行

标签 perl apache bash alias

为了格式化我的 apache error_log 以便查看起来更愉快,我编写了一个快速而肮脏的 perl 脚本。

tail -f /var/log/apache2/error_log | perl -ne 
  '($timeStamp, $error, $hostName, $message) = 
      /^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i; # Parse log
   ($day, $month, $date, $time, $year) = 
      $timeStamp =~ m/(\S*) (\S*) (\S*) (\S*) (\S*)$/; # Extract the timestamp
   $message =~ s/, referer: (.*)$/\./;  # Strip the referer references
   $message =~ s/\\n/\n/g; # Replace literal new lines to expand object dumps
   print $time . " " . $date . " " . $month . " | " . $message ."\n";'

我想将脚本添加到 Bash 别名,以便我可以从终端轻松调用它。

例如

alias te=tail -f /var/log/apache2/error_log | perl -ne '($timeStamp, $error, $hostName, $message) = /^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i; ($day, $month, $date, $time, $year) = $timeStamp =~ m/(\S*) (\S*) (\S*) (\S*) (\S*)$/; $message =~ s/, referer: (.*)$/\./; $message =~ s/\\n/\n/g; print $time . " " . $date . " " . $month . " | " . $message ."\n";'

显然转义引号开始变得困惑。我也试过将 perl 脚本放在它自己的文件中并将其作为别名运行,但我想避免必须在 .bash_profile 文件之外运行脚本以实现可移植性。

如何将 perl 脚本用作 bash 别名/函数?还是我是从完全错误的方向来的?

最佳答案

你绝对应该使用函数而不是别名:

function te ()
{
    tail -f /var/log/apache2/error_log \
    | perl -ne \
       '($timeStamp, $error, $hostName, $message) = 
          /^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i; # Parse log
        ($day, $month, $date, $time, $year) = 
          $timeStamp =~ m/(\S*) (\S*) (\S*) (\S*) (\S*)$/; # Extract the timestamp
        $message =~ s/, referer: (.*)$/\./;  # Strip the referer references
        $message =~ s/\\n/\n/g; # Replace literal new lines to expand object dumps
        print $time . " " . $date . " " . $month . " | " . $message ."\n";
       '
}

关于perl - 难以将 Perl 脚本作为 Bash 别名运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557908/

相关文章:

perl - 如何使正则表达式与 perl 命令一起使用并从文件中提取数字?

javascript - 使用 Javascript 从 Selenium::Remote::Driver 包恢复 Windows "Confirm Box"

mysql - 如何让 XAMPP 控制面板正确安装和启动服务?

bash:列出不具有给定扩展名的文件

bash - 织物运行和直接运行之间的不同结果

Bash测试值评估

perl - 在 EOF 之前的任何地方都找不到字符串终止符 "str"

perl - 如何提取美国国防部契约(Contract)信息以用于统计分析?

apache - 同一域中两个应用程序的 SSL 代理(一个应用程序没有上下文路径)

apache - 使用 Apache Mahout 机器学习库