grep --line-X 라인까지 버퍼링됩니까?

grep --line-X 라인까지 버퍼링됩니까?

로그를 보고 프로그램이 3번 시도했지만 실패했는지 확인하고 싶습니다.

tail -f file.log | grep --line-buffered program\ failed\ string

행 수가 grep3이 되면 오류를 반환하고 싶습니다.

어떻게 해야 하나요?

답변1

스트림을 스캔하는 훌륭한 도구입니다.

귀하의 예와 달리 종료될 때까지 로그를 보려면 모든 행을 표시해야 한다고 생각합니다.grep오류 줄만 표시됩니다.

tail -f file.log | awk '
    BEGIN {
        count = 0
    }

    {
        print($0)

        if ($0 ~ /program failed/) {
            count++
            if (count == 3) {
                exit(1)
            }
        }
    }
'

awk 코드를 다음으로 이동할 수 있습니다.tail.awktail -f file.log | awk -f tail.awk원하시면 전화주세요.

마찬가지로, 더 간결한 형태로:

tail -f file.log | awk '1; /program failed/ && ++count == 3 { exit 1 }'

답변2

누군가가 Python 대안을 선호할 경우를 대비하여:

#!/usr/bin/env python2
# -*- encoding: ascii -*-
"""tail.py"""

import sys
import argparse
import time
import re

# Create a command-line parser
parser = argparse.ArgumentParser()

parser.add_argument(
    "-f", "--input-file",
    help="File to search through.",
    dest="input_file", type=str,
)
parser.add_argument(
    "-p", "--pattern",
    help="Regular expression to match.",
    default=r'.*',
    dest="pattern", type=str,
)
parser.add_argument(
    "-m", "--match-limit",
    help="Number of matches before exiting.",
    default=float(1),
    dest="match_limit", type=int,
)
parser.add_argument(
    "-q", "--quiet",
    help="Don't print matched lines.",
    default=False,
    dest="quiet", type=bool,
)

# Define the file-watching function
def watch_for_matches(file_handle, pattern, match_limit, quiet):

    # Count the number of matched lines
    matches_found = 0

    # Get the next line
    line = file_handle.readline()

    # Check to see if the limit has been reached
    while(matches_found < match_limit):

        # Match the line against the given regular expression
        if(line and re.search(pattern, line)):

            # Optionally print the matched line
            if not quiet:
                sys.stdout.write(line)

            # Increment the match counter
            matches_found += 1

        # Optionally wait for a moment 
        time.sleep(0.25)

        # Get the next line of input
        line = file_handle.readline()

    # If the match limit is reached, exit with an error
    sys.exit(1)

# Parse the command-line arguments
args = parser.parse_args()

# Execute the function
if args.input_file:
    with open(args.input_file, 'r') as file_handle:
        watch_for_matches(file_handle, args.pattern, args.match_limit, args.quiet)

# If no file is given, use standard input instead
else:
    watch_for_matches(sys.stdin, args.pattern, args.match_limit, args.quiet)

관련 정보