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 / 756001
Accepted
peti27
peti27
Asked: 2023-09-07 22:09:54 +0800 CST2023-09-07 22:09:54 +0800 CST 2023-09-07 22:09:54 +0800 CST

Como recriar grep -f com awk

  • 772

Eu tenho um arquivo grande com muitas informações desnecessárias. Estou interessado apenas na seção entre editar e próximo e tratá-los como uma entrada. Eu consigo filtrar assim....

'

awk  'BEGIN {FS = "\n"; RS = ""; OFS = "\n" ;} {if (/intf/ && /addr/) { print $0"\n"}}' > outputfile

Amostra do arquivo de saída mostrado abaixo.

edit 114
set uuid 6cb43
set action accept
set srcintf "Port-ch40.1657"
set dstintf "any"
set srcaddr "1.1.1.1"
set dstaddr "all"
set schedule "always"
set service "ALL_ICMP" "icmp-echo-reply" "icmp-source-quench" "icmp-time-exceeded" "icmp-unreachable"
set logtraffic all
next

edit 330
set uuid 6d3d
set action accept
set srcintf "Po40.28"
set dstintf "any"
set srcaddr "all"
set dstaddr "2.2.2.2"
set schedule "always"
set service "ALL_ICMP" "icmp-echo-reply" "icmp-source-quench" "icmp-time-exceeded" "icmp-unreachable"
set logtraffic all
next

existe uma opção com grep onde os valores podem vir de um arquivo (grep -f filterfile textfile). Vamos supor que filterfile contenha os valores ...

1.1.1.1
3.3.3.3

Na realidade, seria muito mais que a entrada manual poderia não estar funcionando.

awk  'BEGIN {FS = "\n"; RS = ""; OFS = "\n" ;} {if (/intf/ && /addr/ &&(/1.1.1.1/||/3.3.3.3/)) { print $0"\n"}}' > outputfile

O comando awk pode ser modificado para lidar com valores provenientes de um arquivo?

awk  'BEGIN {FS = "\n"; RS = ""; OFS = "\n" ;} {if (/intf/ && /addr/ &&(values_from_filterfile)) { print $0"\n"}}' > outputfile
awk
  • 3 3 respostas
  • 90 Views

3 respostas

  • Voted
  1. Olivier Dulac
    2023-09-07T22:48:19+08:002023-09-07T22:48:19+08:00

    se for seu:

    awk 'BEGIN {FS = "\n"; RS = ""; OFS = "\n" ;} {if (/intf/ && /addr/ &&(/1.1.1.1/||/3.3.3.3/)) { print $0"\n"}}' > outputfile
    

    é realmente o que você precisa fazer, você pode combinar coisas de um arquivo "match.list" contendo em cada linha algum endereço IP com:

    gawk '
      ( NR==FNR ) { # NR==FNR only when parsing the first file...
          ipreg=$0; # get one ip from the first file
          gsub(".", "\.", ipreg); #ensure each "." becomes "\." for the regex
          ipreg= "\<" ipreg "\>" # add beginning of word / end of word delimiters
          # that way 1.2.3.4 will NOT match: 11.2.3.42
          ipsreg=ipsreg sep ipreg; sep="|" # add it to the list of ipsreg
          # and sep only added before the 2+ elements as it is an empty string for the 1st
          next # skip everything else, we are parsing the first file...
        }
    
      
        ( /intf/ && /addr/ && ( $0 ~ ipsreg ) ) # default action will be print $0 if it matches...
        # and as ORS at that point will have been set to "\n\n",
        # it will print the record + an empty line after it
     ' match.list FS="\n" RS="" OFS="\n" ORS="\n\n" - > outputfile
       # the things between match.list and - will be seen as definitions to be done at that time,
       # as they contain a "=", and not be interpreted as filenames
       #  - : is STDIN, and will be the 2nd "file" parsed, where NR>FNR (FNR=for the current file, NR=from the beginning)
    
    • 1
  2. Best Answer
    Ed Morton
    2023-09-08T18:14:19+08:002023-09-08T18:14:19+08:00

    FWIW, eu não usaria regexps para isso, eu criaria um array ( v[]) abaixo que mapeia tags como srcaddrseus valores como "1.1.1.1"ou "all"e então você pode fazer uma pesquisa de hash dos índices do array para descobrir quais tags estão presentes no bloco atual e quais valores as tags de seu interesse possuem. Por exemplo, usando qualquer awk POSIX:

    $ cat tst.awk
    NR==FNR {
        ips["\"" $0 "\""]
        next
    }
    $1 == "edit" {
        lineNr = 1
    }
    lineNr {
        tagFld = (NF > 2 ? 2 : 1)
        tag = $tagFld
        match($0,"^([[:space:]]*[^[:space:]]+){" tagFld "}[[:space:]]*")
        heads[tag] = substr($0,1,RLENGTH)
        v[tag] = substr($0,RLENGTH+1)
        tags[lineNr++] = tag
    
        if ( $1 == "next" ) {
            if (    (("srcintf" in v) && (v["srcaddr"] in ips)) \
                 || (("dstintf" in v) && (v["dstaddr"] in ips)) \
               ) {
                for ( i=1; i<lineNr; i++ ) {
                    tag = tags[i]
                    print heads[tag] v[tag]
                }
                print ""
            }
            delete v
            lineNr = 0
        }
    }
    

    $ awk -f tst.awk filterfile textfile
    edit 114
    set uuid 6cb43
    set action accept
    set srcintf "Port-ch40.1657"
    set dstintf "any"
    set srcaddr "1.1.1.1"
    set dstaddr "all"
    set schedule "always"
    set service "ALL_ICMP" "icmp-echo-reply" "icmp-source-quench" "icmp-time-exceeded" "icmp-unreachable"
    set logtraffic all
    next
    

    Com essa estrutura, você pode testar ou alterar trivialmente quaisquer valores de quaisquer tags que desejar e escrever testes muito mais precisos para o que você deseja que seja o conteúdo de cada tag em cada bloco, em vez de apenas fazer uma comparação de regexp em todo o bloco. Por exemplo, se você quiser encontrar/exibir os blocos onde uuidis 6cb43, scheduleis alwayse serviceinclude "icmp-time-exceeded"você pode simplesmente alterar isto:

            if (    (("srcintf" in v) && (v["srcaddr"] in ips)) \
                 || (("dstintf" in v) && (v["dstaddr"] in ips)) \
    

    para isso:

            if (    (v["uuid"] == "6cb43") \
                 && (v["schedule"] == "always") \
                 && (v["service"] ~ /"icmp-time-exceeded"/) \
    

    e se você quiser definir qualquer tag com algum outro valor antes de imprimir, basta preenchê-lo v[]antes do loop de impressão:

    $ cat tst.awk
    NR==FNR {
        ips["\"" $0 "\""]
        next
    }
    $1 == "edit" {
        lineNr = 1
    }
    lineNr {
        tagFld = (NF > 2 ? 2 : 1)
        tag = $tagFld
        match($0,"^([[:space:]]*[^[:space:]]+){" tagFld "}[[:space:]]*")
        heads[tag] = substr($0,1,RLENGTH)
        v[tag] = substr($0,RLENGTH+1)
        tags[lineNr++] = tag
    
        if ( $1 == "next" ) {
            if (    (("srcintf" in v) && (v["srcaddr"] in ips)) \
                 || (("dstintf" in v) && (v["dstaddr"] in ips)) \
               ) {
                v["action"] = "reject"
                v["dstaddr"] = "\"127.0.0.1\""
                for ( i=1; i<lineNr; i++ ) {
                    tag = tags[i]
                    print heads[tag] v[tag]
                }
                print ""
            }
            delete v
            lineNr = 0
        }
    }
    

    $ awk -f tst.awk filterfile textfile
    edit 114
    set uuid 6cb43
    set action reject
    set srcintf "Port-ch40.1657"
    set dstintf "any"
    set srcaddr "1.1.1.1"
    set dstaddr "127.0.0.1"
    set schedule "always"
    set service "ALL_ICMP" "icmp-echo-reply" "icmp-source-quench" "icmp-time-exceeded" "icmp-unreachable"
    set logtraffic all
    next
    
    • 0
  3. meuh
    2023-09-08T22:08:31+08:002023-09-08T22:08:31+08:00

    Para responder apenas ao ponto específico, o awk pode manipular valores provenientes de um arquivo , sim, você pode redirecionar a entrada para um getlinecomando usando <o nome do arquivo. Adicione ao final do seu bloco BEGIN:

    getline <"filterfile";
    fromfilter = $0;
    gsub("\n","|",fromfilter);
    

    Como você já configurou FS e RS, getlineirá ler o arquivo inteiro $0, então basta substituir os separadores de linha pelo |operador regexp. Use a variável resultante com match:

    if (/intf/ && /addr/ && match($0,fromfilter)) { print $0"\n"}
    
    • 0

relate perguntas

  • remova o número de linhas duplicadas com base na correspondência antes da primeira vírgula

  • anexar linhas após outros arquivos linha por linha

  • Como remover uma única linha entre duas linhas

  • Reorganize as letras e compare duas palavras

  • Embaralhamento de arquivo de várias linhas

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