我试图找到一个简洁的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)
当然,你可以更有效地打开文件,寻找到最后并回头找到匹配的行.
在 …