我试图找到一个简洁的贝壳单线,它会给我所有的
文件中的行直到某个模式.
文件中的行直到某个模式.
用例是将所有行转储到日志文件中,直到找到一些为止
表示服务器已重新启动的标记.
这是一种愚蠢的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
- }
- 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];
- }
- '
当然,你可以更有效地打开文件,
寻求最终并寻找回来,直到找到匹配的行.
从第一次出现时很容易打印所有内容,例如:
- sed -n '/PATTERN/,$p'