Obtendo a última correspondência em um arquivo usando grep

44

Qual é a melhor maneira de obter apenas a correspondência final de uma expressão regular em um arquivo usando o grep?

Além disso, é possível começar a usar o final do arquivo em vez do início e parar quando encontrar a primeira correspondência?

    
por Acorn 02.11.2010 / 00:26

3 respostas

68

Você poderia tentar

grep pattern file | tail -1

ou

tac file | grep pattern | head -1

ou

tac file | grep -m1 pattern
    
por 02.11.2010 / 00:33
1

Estou sempre usando o cat (mas isso faz com que seja um pouco mais longo): cat file | grep pattern | tail -1

Eu culparia meu professor do curso linux admin na faculdade que ama gatos:))))

- Você não precisa colocar um arquivo antes de aplicá-lo. grep pattern file | tail -1 e é mais eficiente também.

    
por 02.11.2010 / 02:45
0

Para alguém que trabalha com arquivos de texto enormes no Unix / Linux / Mac / Cygwin. Se você usa o Windows, confira as ferramentas do Linux no Windows: link .

Pode-se seguir este fluxo de trabalho para ter um bom desempenho:

  1. comprima com gzip
  2. use zindex (no github:      link ) para indexar o arquivo com     chave apropriada
  3. consulte o arquivo indexado com zq do pacote.

Cite seu leia-me do github:

Criando um índice

zindex needs to be told what part of each line constitutes the index. This can be done by a regular expression, by field, or by piping each line through an external program.

By default zindex creates an index of file.gz.zindex when asked to index file.gz.

Example:

create an index on lines matching a numeric regular expression. The capture group indicates the part that's to be indexed, and the options show each line has a unique, numeric index.

$ zindex file.gz --regex 'id:([0-9]+)' --numeric --unique

Example: create an index on the second field of a CSV file:

$ zindex file.gz --delimiter , --field 2 

Example:

create an index on a JSON field orderId.id in any of the items in the document root's actions array (requires jq). The jq query creates an array of all the orderId.ids, then joins them with a space to ensure each individual line piped to jq creates a single line of output, with multiple matches separated by spaces (which is the default separator).

$ zindex file.gz --pipe "jq --raw-output --unbuffered '[.actions[].orderId.id] | join(\" \")'" 

Consultando o índice

The zq program is used to query an index. It's given the name of the compressed file and a list of queries. For example:

$ zq file.gz 1023 4443 554 

It's also possible to output by line number, so to print lines 1 and 1000 from a file:

$ zq file.gz --line 1 1000
    
por 03.10.2016 / 09:39