在文件名中包含变量perl

在文件名中包含变量perl

问题描述:

我正在尝试创建一个脚本,用于搜索日志文件中的特定错误。日志文件是加盖日期的,所以我只想查看今天的日志文件。这将最终成为cronjob。当我运行这个。目前,我得到下面的错误:在文件名中包含变量perl

tail: cannot open `/var/log/file.2014-09-03-Wed\n.log' for reading: No such file or directory

所以我得到的日期,但后来有一个\ n的加入。以下脚本:

$date=`date +"%Y-%m-%d-%a"`; 
$string = `tail -n50 /var/log/"file.$date.log" | grep -B2 'Too many connected clients'`; 

if($string =~ m/Reply: 421 Service not available. There are too many connected users, please try later/){ 
print "Max connections reached $date" 
} 

任何意见将不胜感激!

+1

?也许一个简单的bash脚本.... – jm666 2014-09-03 11:48:22

+0

或者,重写perl文件的阅读和日期格式是非常基本的perl操作。 – Sobrique 2014-09-03 12:16:36

+0

我做了很多bash,但是为了工作目的学习perl。 – user3573036 2014-09-04 14:43:07

尝试使用chomp($data)$date =~s/\n//;

取出\n$date

chomp($date); 
+0

$ date ='date +“%Y-%m-%d-%a”'; chomp($ date); $ string ='tail -n50'/var/log/file.$date.log'| grep -B2'连接的客户端太多'; if($ string =〜m/Reply:421服务不可用,连接的用户太多,请稍后尝试/){ print“已到达最大连接数$ date” } – user3573036 2014-09-03 11:23:04

+0

@ user3573036:对不起,没有你。 “chomp”不是解决问题的方法吗? – Toto 2014-09-03 11:28:37

+0

@ user3573036:请问这个问题的状态如何?为什么你发布了一段代码作为评论? – Borodin 2014-09-04 13:15:28

使用Time::Piece模块获得格式化日期和时间,而不是开始一个整体的其他过程做到这一点。它是Perl 5版本10以来的核心模块,所以不需要安装,除非你的Perl很老。

它看起来像你为什么用perl,如果行的50%是外部命令这

use Time::Piece; 

my $date = localtime->strftime('%Y-%m-%d-%a'); 
print $date, "\n"; 

输出

2014-09-03-Wed