AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / unix / Perguntas / 406630
Accepted
Philip Kirkbride
Philip Kirkbride
Asked: 2017-11-24 10:06:11 +0800 CST2017-11-24 10:06:11 +0800 CST 2017-11-24 10:06:11 +0800 CST

grep --line-buffered até X linhas?

  • 772

Estou assistindo a um log e quero detectar uma vez que um programa teve 3 tentativas malsucedidas:

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

Se a contagem de linhas grepatingir 3, quero retornar um erro.

Como posso fazer isso?

grep
  • 2 2 respostas
  • 977 Views

2 respostas

  • Voted
  1. Best Answer
    user285259
    2017-11-24T10:32:52+08:002017-11-24T10:32:52+08:00

    awk é uma ótima ferramenta para escanear streams.

    Presumi que deveria exibir todas as linhas para ver o log até sair, ao contrário do seu exemplo com grep que exibe apenas linhas de erro.

    tail -f file.log | awk '
        BEGIN {
            count = 0
        }
    
        {
            print($0)
    
            if ($0 ~ /program failed/) {
                count++
                if (count == 3) {
                    exit(1)
                }
            }
        }
    '
    

    Você pode mover o código awk para tail.awk e chamar tail -f file.log | awk -f tail.awkse preferir.

    Equivalentemente, de uma forma mais compacta:

    tail -f file.log | awk '1; /program failed/ && ++count == 3 { exit 1 }'
    
    • 6
  2. igal
    2017-11-24T11:25:58+08:002017-11-24T11:25:58+08:00

    Apenas no caso de alguém preferir uma alternativa 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)
    
    • 2

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Matriz JSON para bash variáveis ​​usando jq

    • 4 respostas
  • Marko Smith

    A data pode formatar a hora atual para o fuso horário GMT? [duplicado]

    • 2 respostas
  • Marko Smith

    bash + lê variáveis ​​e valores do arquivo pelo script bash

    • 4 respostas
  • Marko Smith

    Como posso copiar um diretório e renomeá-lo no mesmo comando?

    • 4 respostas
  • Marko Smith

    conexão ssh. Conexão X11 rejeitada devido a autenticação incorreta

    • 3 respostas
  • Marko Smith

    Como baixar o pacote não instalá-lo com o comando apt-get?

    • 7 respostas
  • Marko Smith

    comando systemctl não funciona no RHEL 6

    • 3 respostas
  • Marko Smith

    rsync porta 22 e 873 uso

    • 2 respostas
  • Marko Smith

    snap /dev/loop em 100% de utilização -- sem espaço livre

    • 1 respostas
  • Marko Smith

    chave de impressão jq e valor para todos no subobjeto

    • 2 respostas
  • Martin Hope
    EHerman Matriz JSON para bash variáveis ​​usando jq 2017-12-31 14:50:58 +0800 CST
  • Martin Hope
    Christos Baziotis Substitua a string em um arquivo de texto enorme (70 GB), uma linha 2017-12-30 06:58:33 +0800 CST
  • Martin Hope
    Drux A data pode formatar a hora atual para o fuso horário GMT? [duplicado] 2017-12-26 11:35:07 +0800 CST
  • Martin Hope
    AllisonC Como posso copiar um diretório e renomeá-lo no mesmo comando? 2017-12-22 05:28:06 +0800 CST
  • Martin Hope
    Steve Como as permissões de arquivo funcionam para o usuário "root"? 2017-12-22 02:46:01 +0800 CST
  • Martin Hope
    Bagas Sanjaya Por que o Linux usa LF como caractere de nova linha? 2017-12-20 05:48:21 +0800 CST
  • Martin Hope
    Cbhihe Altere o editor padrão para vim para _ sudo systemctl edit [unit-file] _ 2017-12-03 10:11:38 +0800 CST
  • Martin Hope
    showkey Como baixar o pacote não instalá-lo com o comando apt-get? 2017-12-03 02:15:02 +0800 CST
  • Martin Hope
    youxiao Por que os diretórios /home, /usr, /var, etc. têm o mesmo número de inode (2)? 2017-12-02 05:33:41 +0800 CST
  • Martin Hope
    user223600 gpg — o comando list-keys gera uid [ desconhecido ] depois de importar a chave privada para uma instalação limpa 2017-11-26 18:26:02 +0800 CST

Hot tag

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve