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

时间:2012-09-24 01:47:08

标签: 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别名中,以便我可以从终端轻松调用它。

e.g。

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别名/函数?还是我从完全错误的方向来到这里?

2 个答案:

答案 0 :(得分:6)

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

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";
       '
}

答案 1 :(得分:0)

更改

alias te=tail -f /var/log/apache2/error_log | perl -ne '...'

alias te='tail -f /var/log/apache2/error_log | perl -ne '\''...'\'''