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 / 787693
Accepted
learningregularexpressions
learningregularexpressions
Asked: 2024-12-06 02:38:40 +0800 CST2024-12-06 02:38:40 +0800 CST 2024-12-06 02:38:40 +0800 CST

Imprimindo uma seção específica sempre que os resultados da pesquisa forem correspondidos

  • 772

Tenho um arquivo de texto bem básico em uma máquina Linux que contém coisas como capítulos, diálogos e referências.

É assim que parece


Chapter: 1 One: Birds and Trees

Birds are beautiful and trees are amazing and
they are dependent on each other. Birds most of the time
choose to make their nests on trees since trees provide more
stability. One day the bird sat on a tree and said;

Bird: Oh my I'm so tired from all the flying, I should take a rest
Tree: Mr Bird, you seem tired, perhaps you should take some rest, and
here are some fruits to quench your thirst.
Bird: Oh thank you very much!

Reference:               Chapter 1: birds and trees

Chapter: 2 Two: Trees and Fruits

Fruits are very delicious to eat and they are mostly found
in trees. Fruits contain essential vitamins, minerals and loads
of good fibers.

Reference:               Chapter 2: trees and fruits

Este é o conteúdo do arquivo txt. Agora, digamos que eu estava procurando por quench, eu estava pensando que começaria do número do Capítulo até a Referência. Então eu tentei com grep;

$ grep -A 5 -B 5 'quench' file.txt

No entanto, isso não produz a saída desejada. Eu esperava algo assim;

Chapter: 1 One: Birds and Trees

Birds are beautiful and trees are amazing and
they are dependent on each other. Birds most of the time
choose to make their nests on trees since trees provide more
stability. One day the bird sat on a tree and said;

Bird: Oh my I'm so tired from all the flying, I should take a rest
Tree: Mr Bird, you seem tired, perhaps you should take some rest, and
here are some fruits to quench your thirst.
Bird: Oh thank you very much!

Reference:               Chapter 1: birds and trees

E também, pesquisar pela palavra "vitamina" retornaria;

Chapter: 2 Two: Trees and Fruits

Fruits are very delicious to eat and they are mostly found
in trees. Fruits contain essential vitamins, minerals and loads
of good fibers.

Reference:               Chapter 2: trees and fruits

Eu queria saber se isso seria possível através do sed ou awk.

PS: Cada nova linha é uma nova linha de verdade

shell-script
  • 2 2 respostas
  • 49 Views

2 respostas

  • Voted
  1. Best Answer
    markp-fuso
    2024-12-06T03:25:49+08:002024-12-06T03:25:49+08:00

    Uma awkideia:

    awk -v word="quench" '                                            # set variable "word" to string we are searching for
    /^Chapter:/      { inblock = 1; block = "" }                      # start of new block; set flag and clear block
    
    inblock          { block = block (block == "" ? "" : ORS) $0 }    # if inblock != 0 then append current line to "block"
    
    /^Reference:/ &&                                                  # if end of block and ...
    block ~ word     { print block; inblock = 0 }                     # word is in block then print block; clear flag
    ' file.txt
    

    Com -v word="quench"isso gera:

    Chapter: 1 One: Birds and Trees
    
    Birds are beautiful and trees are amazing and
    they are dependent on each other. Birds most of the time
    choose to make their nests on trees since trees provide more
    stability. One day the bird sat on a tree and said;
    
    Bird: Oh my I'm so tired from all the flying, I should take a rest
    Tree: Mr Bird, you seem tired, perhaps you should take some rest, and
    here are some fruits to quench your thirst.
    Bird: Oh thank you very much!
    
    Reference:               Chapter 1: birds and trees
    

    Com -v word="essential"isso gera:

    Chapter: 2 Two: Trees and Fruits
    
    Fruits are very delicious to eat and they are mostly found
    in trees. Fruits contain essential vitamins, minerals and loads
    of good fibers.
    
    Reference:               Chapter 2: trees and fruits
    

    Com -v word="bubble", ou quando nenhuma -v word=...cláusula é fornecida, isso gera:

    -- no output
    
    • 2
  2. jubilatious1
    2024-12-06T18:41:15+08:002024-12-06T18:41:15+08:00

    Usando Raku (anteriormente conhecido como Perl_6)

    ~$ raku -e 'my @a; 
                for slurp() { 
                    @a = .comb(/^^ Chapter  .*?  <?before \nChapter | $ > /) 
                };  @a.grep(/quench/).put;'  file
    

    Certamente alguém postará uma resposta em Perl, mas aqui está uma resposta escrita em Raku (também conhecido como Perl6). O Raku fornece suporte de alto nível para Unicode, integrado.

    Resumidamente, o arquivo é slurpeditado e combeditado para localizar registros correspondentes (Capítulos). Então, na declaração final, grepé usado para retornar apenas registros correspondentes (Capítulos). A entrada de amostra é a mesma fornecida pelo OP.

    Exemplo de saída:

    Chapter: 1 One: Birds and Trees
    
    Birds are beautiful and trees are amazing and
    they are dependent on each other. Birds most of the time
    choose to make their nests on trees since trees provide more
    stability. One day the bird sat on a tree and said;
    
    Bird: Oh my I'm so tired from all the flying, I should take a rest
    Tree: Mr Bird, you seem tired, perhaps you should take some rest, and
    here are some fruits to quench your thirst.
    Bird: Oh thank you very much!
    
    Reference:               Chapter 1: birds and trees
    
    

    Adicione chamadas para trim, trim-leadingou trim-trailingna declaração final para remover os espaços em branco ao redor, conforme desejado.

    https://raku.org

    • 0

relate perguntas

  • Subtraindo a mesma coluna entre duas linhas no awk

  • Um script que imprime as linhas de um arquivo com seu comprimento [fechado]

  • exportar variáveis ​​​​env programaticamente, via stdout do comando [duplicado]

  • Dividir por delimitador e concatenar problema de string

  • MySQL Select com função IN () com array bash

Sidebar

Stats

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

    Possível firmware ausente /lib/firmware/i915/* para o módulo i915

    • 3 respostas
  • Marko Smith

    Falha ao buscar o repositório de backports jessie

    • 4 respostas
  • Marko Smith

    Como exportar uma chave privada GPG e uma chave pública para um arquivo

    • 4 respostas
  • Marko Smith

    Como podemos executar um comando armazenado em uma variável?

    • 5 respostas
  • Marko Smith

    Como configurar o systemd-resolved e o systemd-networkd para usar o servidor DNS local para resolver domínios locais e o servidor DNS remoto para domínios remotos?

    • 3 respostas
  • Marko Smith

    apt-get update error no Kali Linux após a atualização do dist [duplicado]

    • 2 respostas
  • Marko Smith

    Como ver as últimas linhas x do log de serviço systemctl

    • 5 respostas
  • Marko Smith

    Nano - pule para o final do arquivo

    • 8 respostas
  • Marko Smith

    erro grub: você precisa carregar o kernel primeiro

    • 4 respostas
  • Marko Smith

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

    • 7 respostas
  • Martin Hope
    user12345 Falha ao buscar o repositório de backports jessie 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl Por que a maioria dos exemplos do systemd contém WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky Como exportar uma chave privada GPG e uma chave pública para um arquivo 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll status systemctl mostra: "Estado: degradado" 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim Como podemos executar um comando armazenado em uma variável? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S Por que /dev/null é um arquivo? Por que sua função não é implementada como um programa simples? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 Como ver as últimas linhas x do log de serviço systemctl 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - pule para o final do arquivo 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla Por que verdadeiro e falso são tão grandes? 2018-01-26 12:14:47 +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

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