2012-09-24 67 views
2

要格式化我的apache error_log,以便更加愉快地看我寫了一個快速且髒的perl腳本。難以將Perl腳本作爲Bash別名運行

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別名/函數?還是我從完全錯誤的方向來到這裏?

回答

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

感謝您的迅速回復!這就像夢一樣!我之前嘗試過,但我必須有一些時髦的.alias宿醉優先。 – sebastiansibelle

+0

@sebastiansibelle:不客氣! – ruakh

0

變化

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

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