perl 在包含搜索字符串之后抓取文件的一部分: [英] perl grab part of file after and including search string:

查看:36
本文介绍了perl 在包含搜索字符串之后抓取文件的一部分:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要搜索一个文件,然后返回包含搜索字符串和搜索字符串之后的内容.上下文正在搜索一个日志文件,我想在其中返回从某个日期开始的所有消息 > 最后一个时间戳.示例子字符串可能是:[Mon Oct 13 20:11:32 2014]".

i need to search a file then return contents including, and after a search string. the context is searching a log file where i want to return all messages beginning on a date > the last time stamp. example substring might be: "[Mon Oct 13 20:11:32 2014]".

我已经打开了一个日志文件,将其写入另一个文件.现在我想将第二个文件减少为包含子字符串和子字符串之后的部分.

i have already opened a log file, written it into another file. now i want to reduce the 2nd file to be just the part including and after the substring.

我见过很多令人费解的正则表达式等,而且我是 Perl 的新手,我想知道这只是我一个人的问题,还是一个答案正盯着我看?任何简单的事情,都将不胜感激!

i have seen lots of convoluted regex, etc. and being new to Perl am wondering if it's just me, or is an answer staring me in the face? anything simple, to the point would be much appreciated!

这是我目前所拥有的:

open(FILE, "/opt/workid/logs/error_log") or die "ERROR:cannot open file $!";
open(FILE2, "/opt/workid/logs/output.txt") or die "ERROR:canont open file $!";
if ( /\Q[Mon Oct 13 20:11:32 2014]\E/ ) {
    $var = 1
} if ( $var ) {
    print "/opt/workid/logs/error_log" > "/opt/workid/logs/output.txt"
}

推荐答案

您的代码的问题之一是以下语法:

One of the problems with your code is this syntax:

print "/opt/workid/logs/error_log" > "/opt/workid/logs/output.txt"

这在 Perl 中无效.您还想使用 open 和词法文件句柄的 3 参数形式.我将您的代码放入未经测试的脚本中并进行了一些修改.

This isn't valid in Perl. You also want to use the 3 argument form of open and lexical filehandles. I put your code into an untested script and made some modifications.

#!/usr/bin/perl
use strict;
use warnings;
open(my $err_fh, '<', "/opt/workid/logs/error_log") or die "ERROR:cannot open file $!"; # open file for reading
open(my $out_fh, '>', "/opt/workid/logs/output.txt") or die "ERROR:cannot open file $!"; # open file for writing
my $var = 0;
while ( <$err_fh> ) { # go through the error log line by line
    if ( /\Q[Mon Oct 13 20:11:32 2014]\E/ ) { # found the timestamp.
        $var = 1;
    }
    if ( $var ) { # print everything after finding the timestamp
        print $out_fh $_;
    }
}

运行:

perl script.pl

如果运行这个有任何问题,请告诉我!

Let me know if there are any problems running this!

这篇关于perl 在包含搜索字符串之后抓取文件的一部分:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆