小编Æva*_*son的帖子

简洁的方式将所有行打印到与给定模式匹配的最后一行

我试图找到一个简洁的shell单行程序,它会在文件中提供所有行,直到某种模式.

用例是将所有行转储到日志文件中,直到我发现一些标记表明服务器已重新启动.

这是一种愚蠢的shell专用方式:

tail_file_to_pattern() {
    pattern=$1
    file=$2

    tail -n$((1 + $(wc -l $file | cut -d' ' -f1) - $(grep -E -n "$pattern" $file | tail -n 1 | cut -d ':' -f1))) $file
}
Run Code Online (Sandbox Code Playgroud)

在stdin上获取文件的稍微更可靠的Perl方式:

perl -we '
    push @lines => $_ while <STDIN>;
    my $pattern = $ARGV[0];
    END {
        my $last_match = 0;
        for (my $i = @lines; $i--;) {
            $last_match = $i and last if $lines[$i] =~ /$pattern/;
        }
        print @lines[$last_match..$#lines];
    }
'
Run Code Online (Sandbox Code Playgroud)

当然,你可以更有效地打开文件,寻找到最后并回头找到匹配的行.

在 …

linux shell perl tail

7
推荐指数
2
解决办法
4474
查看次数

标签 统计

linux ×1

perl ×1

shell ×1

tail ×1