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 / 784856
Accepted
ranjit abraham
ranjit abraham
Asked: 2024-10-10 22:45:52 +0800 CST2024-10-10 22:45:52 +0800 CST 2024-10-10 22:45:52 +0800 CST

Comando sed não corresponde e substitui padrão em xml de várias linhas

  • 772

Tenho muitos arquivos XML como abaixo, onde gostaria de substituir uma string por uma nova string. Não consigo fazer o comando sed funcionar nos arquivos XML.

<form version="1.1" theme="dark">
  <label>Forcepoint DLP Dashboard - LongTerm</label>
  <description>Activity for those with Long-Term Exceptions</description>
  <fieldset submitButton="false" autoRun="false">
    <input type="time" token="TimeFrame" searchWhenChanged="true">
      <label>Timeframe</label>
      <default>
        <earliest>-48h@h</earliest>
        <latest>now</latest>
      </default>
    </input>
  </fieldset>
  <row>
    <panel>
      <html>
        <p>Macros In Use:</p>
        <p>`ForcepointApprovedUSB` = Known Approved USB Devices</p>
        <p>`ForcepointKnownCDDVD` = Known CD/DVD Drives</p>
        <p>`ForcepointKnownMultiFunction` = Known Multi-Function Devices</p>
      </html>
    </panel>
  </row>
  <row>
    <panel>
      <title>Exception Info</title>
      <table>
        <search>
          <query>index=restricted_security 
sourcetype=forcepoint 
| rex field=_raw "(.*act=(?&lt;Action&gt;.*?)\s.*)"
| rex field=_raw "(.*duser=(?&lt;Device&gt;.*?)(:\s\d|;|\sfname=).*)"
| rex field=_raw "(.*duser=.*?;\s(?&lt;Serial&gt;.*?)\sfname=)"
| rex field=_raw "(.*fname=(?&lt;Filename&gt;.*?)\smsg=.*)"
| rex field=_raw "(.*fname=.:\\\(?&lt;RawFilename&gt;.*)(?:\s-\s.*)\smsg=.*)"
| rex field=_raw "(.*suser=(?&lt;Name&gt;.*)\scat=.*)"
| rex field=_raw "(.*loginName=.*\\\\(?&lt;Username&gt;.*)\ssourceIp=.*)"
| rex field=_raw "(.*sourceIp=(?&lt;IP&gt;.*)\sseverityType=.*)"
| rex field=_raw "(.*sourceHost=(?&lt;Source&gt;.*)\sproductVersion=.*)"
| rex field=_raw "(.*sourceServiceName=(?&lt;AlertType&gt;.*)\sanalyzedBy=.*)"
| eval Username=lower(Username)
| eval Action=if(isnull(Action),"-",Action)
| eval Serial=if(isnull(Serial),"-",Serial)
| eval EnumDeviceType=case(
    (`ForcepointApprovedUSB`),"ApprovedUSB",
    (`ForcepointKnownCDDVD`),"CDDVD",
    (`ForcepointKnownMultiFunction`),"MultiFunction",
    AlertType="Endpoint Applications" AND Device="Bluetooth","Bluetooth",
    AlertType="Endpoint Removable Media" AND Device="Windows Portable Device (WPD)","WPD",
    AlertType="Endpoint Removable Media" AND 
        Device!="Windows Portable Device (WPD)" AND NOT 
        (`ForcepointApprovedUSB`) AND NOT 
        (`ForcepointKnownCDDVD`) AND NOT 
        (`ForcepointKnownMultiFunction`),"UnApprovedUSB")
| join type=inner Username
[
    search
    index=restricted_security
    sourcetype=dlp_lt
    | rename UserID as Username
    | eval Check = "Yes"
    | fields Username,Check,Justification,Type,ExpireDate
]
| where isnotnull(EnumDeviceType) AND Check="Yes"
| eval Time=strftime(_time, "%B %d, %Y %H:%M %Z")
| dedup Username
| table Time Username Name Justification Type ExpireDate
| sort Name</query>
          <earliest>$TimeFrame.earliest$</earliest>
          <latest>$TimeFrame.latest$</latest>
        </search>
        <option name="drilldown">none</option>
        <option name="refresh.display">progressbar</option>
      </table>
    </panel>
  </row>
  <row>
    <panel>
      <title>Transfers By Those With Long-Term Exceptions</title>
      <table>
        <search>
          <query>index=restricted_security 
sourcetype=forcepoint 
| rex field=_raw "(.*act=(?&lt;Action&gt;.*?)\s.*)"
| rex field=_raw "(.*duser=(?&lt;Device&gt;.*?)(:\s\d|;|\sfname=).*)"
| rex field=_raw "(.*duser=.*?;\s(?&lt;Serial&gt;.*?)\sfname=)"
| rex field=_raw "(.*fname=(?&lt;Filename&gt;.*?)\smsg=.*)"
| rex field=_raw "(.*fname=.:\\\(?&lt;RawFilename&gt;.*)(?:\s-\s.*)\smsg=.*)"
| rex field=_raw "(.*suser=(?&lt;Name&gt;.*)\scat=.*)"
| rex field=_raw "(.*loginName=.*\\\\(?&lt;Username&gt;.*)\ssourceIp=.*)"
| rex field=_raw "(.*sourceIp=(?&lt;IP&gt;.*)\sseverityType=.*)"
| rex field=_raw "(.*sourceHost=(?&lt;Source&gt;.*)\sproductVersion=.*)"
| rex field=_raw "(.*sourceServiceName=(?&lt;AlertType&gt;.*)\sanalyzedBy=.*)"
| eval Username=lower(Username)
| eval Action=if(isnull(Action),"-",Action)
| eval Serial=if(isnull(Serial),"-",Serial)
| eval EnumDeviceType=case(
    (`ForcepointApprovedUSB`),"ApprovedUSB",
    (`ForcepointKnownCDDVD`),"CDDVD",
    (`ForcepointKnownMultiFunction`),"MultiFunction",
    AlertType="Endpoint Applications" AND Device="Bluetooth","Bluetooth",
    AlertType="Endpoint Removable Media" AND Device="Windows Portable Device (WPD)","WPD",
    AlertType="Endpoint Removable Media" AND 
        Device!="Windows Portable Device (WPD)" AND NOT 
        (`ForcepointApprovedUSB`) AND NOT 
        (`ForcepointKnownCDDVD`) AND NOT 
        (`ForcepointKnownMultiFunction`),"UnApprovedUSB")
| join type=inner Username
[
    search
    index=restricted_emn_security
    sourcetype=dlp_lt
    | rename UserID as Username
    | eval Check = "Yes"
    | dedup Username
    | fields Username, Check
]
| where isnotnull(EnumDeviceType) AND Check="Yes"
| eval Time=strftime(_time, "%B %d, %Y %H:%M %Z")
| table Time Username Name Action Source Filename Device Serial EnumDeviceType
| sort -Time</query>
          <earliest>$TimeFrame.earliest$</earliest>
          <latest>$TimeFrame.latest$</latest>
        </search>
        <option name="count">30</option>
        <option name="drilldown">none</option>
      </table>
    </panel>
  </row>
</form>

O padrão que eu gostaria de substituir é

index=restricted_security sourcetype=forcepoint

com

index=newname
sourcetype=forcepoint

Então qualquer padrão onde

index=restricted_security
sourcetype=forcepoint

deve ser substituído pelo novo valor.

Os arquivos XML têm muitas combinações como

index=restricted_security
sourcetype=someother value, index=someindex sourcetype=forcepoint

etc, mas não precisam ser substituídos.

Eu tentei muitos padrões como abaixo com muitas combinações de sed, mas não parece funcionar

sed 's/index=restricted_security\s\nsourcetype=forcepoint/index=restricted_security sourcetype=forcepoint/g'

Alguém pode me dizer como fazer para substituir isso?

sed
  • 3 3 respostas
  • 180 Views

3 respostas

  • Voted
  1. Gilles Quénot
    2024-10-10T23:27:55+08:002024-10-10T23:27:55+08:00

    Usando Pythonlxml :

    import re
    from lxml import etree
    
    file_path = '/tmp/file.xml'
    
    tree = etree.parse(file_path)
    root = tree.getroot()
    
    xpath_expression = '//table/search/query/text()'
    text_nodes = root.xpath(xpath_expression)
    
    if text_nodes:
        first_text_node = text_nodes[0]
        lines = first_text_node.splitlines()
        if lines and 'index=restricted_security' in lines[0]:
            lines[0] = 'index=NEW_NAME'
            updated_text = '\n'.join(lines)
            parent_element = first_text_node.getparent()
            parent_element.text = updated_text
            tree.write(file_path, pretty_print=True, xml_declaration=True, encoding='UTF-8')
    

    O script edita o arquivo no local .

    • 6
  2. Gilles Quénot
    2024-10-11T00:14:38+08:002024-10-11T00:14:38+08:00

    Usando xmlstarletcomo comandos shell, em 2 chamadas deste utilitário:

    #!/bin/sh
     
    xmlstarlet sel -t -v '//table/search/query/text()' file.xml > /tmp/temp.txt
    grep 'index=restricted_security' /tmp/temp.txt || exit 0
    xmlstarlet ed -u '//table/search/query' -v "index=NEW_NAME
    $(awk 'NR>1' /tmp/temp.txt)" file.xml
    

    Você pode adicionar o -Lswitch xmlstarlet edse precisar editar no local .

    Você pode até editar o /tmp/temp.txtarquivo, sedse necessário:

    (isso não é XMLnada além de texto após a primeira execução de xmlstarlet)

    #!/bin/sh
     
    xmlstarlet sel -t -v '//table/search/query/text()' file.xml > /tmp/temp.txt
    sed -i 's/index=restricted_security/index=NEW_NAME/' /tmp/temp.txt
    xmlstarlet ed -u '//table/search/query' -v "$(</tmp/temp.txt)" file.xml
    
    • 6
  3. Best Answer
    Ed Morton
    2024-10-11T04:44:51+08:002024-10-11T04:44:51+08:00

    Usando GNU sed para -z, -E, \sabreviação para espaço e limites de palavras \<e \>:

    $ sed -Ez 's/\<(index=)restricted_security(\s+sourcetype=forcepoint)\>/\1newname\2/g' file > o1
    

    $ diff file o1
    28c28
    <           <query>index=restricted_security
    ---
    >           <query>index=newname
    81c81
    <           <query>index=restricted_security
    ---
    >           <query>index=newname
    

    ou se você quisesse as 2 strings concatenadas em uma única linha (não está claro na sua pergunta):

    $ sed -Ez 's/\<(index=)restricted_security\s+(sourcetype=forcepoint)\>/\1newname \2/g' file > o1
    

    $ diff file o1
    28,29c28
    <           <query>index=restricted_security
    < sourcetype=forcepoint
    ---
    >           <query>index=newname sourcetype=forcepoint
    81,82c80
    <           <query>index=restricted_security
    < sourcetype=forcepoint
    ---
    >           <query>index=newname sourcetype=forcepoint
    
    • 4

relate perguntas

  • Linux grep o que no arquivo 1 está no arquivo 2 [duplicado]

  • como grep linhas após a terceira vírgula com condição

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

  • Como posso melhorar este script de conversão de personagens?

  • Como remover uma única linha entre duas 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