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 / user-243694

DonJ's questions

Martin Hope
DonJ
Asked: 2018-03-25 11:04:36 +0800 CST

procurando vários arquivos por uma linha com número maior na coluna 3 das linhas correspondentes

  • 2

Eu tenho vários arquivos com conteúdo semelhante a:

arquivo principal1:

test01:6733:4370:5342
test02:7776:2018:1001
test03:9865:5632:1429
test04:8477:4757:1890
test05:8019:8860:5298
test06:5602:3100:6995
test07:1445:2850:2755
test08:10924:2562:4867
test09:2575:1884:1611

arquivo de exemplo2:

test01:8777:1060:9236
test02:1322:1211:10837
test04:3737:10175:5219
test05:8467:8988:9739
test06:7452:3100:2709
test08:4707:9047:10578
test09:8669:2867:8233
test10:8615:10002:7056

arquivo de exemplo3:

test01:10957:8172:2472
test02:1401:6160:5894
test03:7245:8934:5725
test04:8477:10106:10069
test05:10769:10381:1102
test06:3605:3713:7695
test08:10924:2562:10568
test09:2913:5628:1305
test10:5501:10293:2319

Desejo atualizar cada linha do arquivo1 principal com uma linha de outro arquivo com a mesma primeira coluna e na terceira coluna com o maior número de todos os arquivos.

Apenas as primeiras colunas no arquivo principal devem ser consideradas (test## que existem nos outros arquivos, mas não existem no arquivo principal, devem ser ignorados).

Quando mais linhas são encontradas nos outros arquivos (com maior, mas o mesmo número na 3ª coluna), qualquer (uma) delas pode ser usada para atualizar o arquivo principal.

aqui está a minha solução não ideal

$ awk -F: '{print $1,$3}' main|while read a b;do grep ^${a}: main file*|sort -t":" -rnk4|awk -F: -vb=$b '{if($4>b){print $0;next} else {print ($1=="main")? $0 : NULL}}'|head -1;done
file3:test01:10957:8172:2472
file3:test02:1401:6160:5894
file3:test03:7245:8934:5725
file2:test04:3737:10175:5219
file3:test05:10769:10381:1102
file3:test06:3605:3713:7695
main:test07:1445:2850:2755
file2:test08:4707:9047:10578
file3:test09:2913:5628:1305

como processar todos esses arquivos no awk de uma só vez e fazer o trabalho sem loops while e muitos pipes que tenho em meu comando?

Atualização: @RomanPerekhrest, obrigado por seu código incrível, como adicionar ainda: sufixo atualizado a todas as linhas que vêm de outros arquivos? Eu gostaria de ter algo como:

test01:10957:8172:2472:updated
test02:1401:6160:5894:updated
test03:7245:8934:5725:updated
test04:3737:10175:5219:updated
test05:10769:10381:1102:updated
test06:3605:3713:7695:updated
test07:1445:2850:2755
test08:4707:9047:10578:updated
test09:2913:5628:1305:updated

Atualização: tenho um novo caso, que não previ antes, que é com os outros arquivos tendo valor maior em $ 3, mas também sem dígitos na coluna $ 2 - nesse caso, essa linha (embora $ 3 maior) deve ser ignorada por causa do erro valores em $2.

Para mostrar este caso, usando os arquivos de amostra acima, na linha "test09" do arquivo2, substituo a segunda coluna por "xxxxx" e agora tenho:

$ grep test09 *
file2:test09:xxxxx:2867:8233
file3:test09:2913:5628:1305
main:test09:2575:1884:1611
$ awk -F':' 'FILENAME != "main"{ if ($2~/^[0-9]+/&&(!($1 in a) || ($3 > a[$1]))) { a[$1]=$3; b[$1]=$0 } next }{ if (($1 in a) && (a[$1] > $3)){ print b[$1]":updated"; delete b[$1] } else print  }' file* main
test01:10957:8172:2472:updated
test02:1401:6160:5894:updated
test03:7245:8934:5725:updated
test04:3737:10175:5219:updated
test05:10769:10381:1102:updated
test06:3605:3713:7695:updated
test07:1445:2850:2755
test08:4707:9047:10578:updated
test09:2913:5628:1305:updated <- this is now update from file3

em seguida, alterei o valor de $ 2 na linha "test09" no arquivo3 para não dígitos também:

$ grep test09 *
file2:test09:xxxxx:2867:8233
file3:test09:zzzzz:5628:1305
main:test09:2575:1884:1611
$ awk -F':' 'FILENAME != "main"{ if ($2~/^[0-9]+/&&(!($1 in a) || ($3 > a[$1]))) { a[$1]=$3; b[$1]=$0 } next }{ if (($1 in a) && (a[$1] > $3)){ print b[$1]":updated"; delete b[$1] } else print  }' file* main
test01:10957:8172:2472:updated
test02:1401:6160:5894:updated
test03:7245:8934:5725:updated
test04:3737:10175:5219:updated
test05:10769:10381:1102:updated
test06:3605:3713:7695:updated
test07:1445:2850:2755
test08:4707:9047:10578:updated
test09:2575:1884:1611 <-- this is now from the main file

Embora pareça estar funcionando bem, alguém poderia explicar o segundo "se" no código? Também precisa da condição para $2~/^[0-9]+/também?

{ if (($1 in a) && (a[$1] > $3))
awk gawk
  • 1 respostas
  • 82 Views
Martin Hope
DonJ
Asked: 2018-03-25 04:55:20 +0800 CST

verificador de resposta em um script

  • 0

Eu tenho o seguinte verificador de resposta em um script:

#!/bin/bash

test_fn()
{
WARNFILE=$1
echo
echo "--- BEGIN ---"
cat ${WARNFILE}
echo "--- END ---"
echo

while true; do
    read -r -n 1 -p "Continue? [y/n]: " REPLY
    case $REPLY in
      [yY]) break ;;
      [nNqQ]) echo;exit ;;
      *) printf "\033[31m%s\033[0m\n" " invalid input: ${REPLY}"
    esac
done
}

test_fn /tmp/warning 

Funciona bem...

$ ./test.sh

--- BEGIN ---
test warning
--- END ---

Continue? [y/n]: a invalid input: a
Continue? [y/n]: s invalid input: s
Continue? [y/n]: d invalid input: d
Continue? [y/n]: w invalid input: w
Continue? [y/n]: s invalid input: s
Continue? [y/n]: q
$

...até eu mudar de linha:

test_fn /tmp/warning

com linha:

test_fn /tmp/warning | tee -a /tmp/logfile

então, embaralha as linhas:

$ ./test.sh

--- BEGIN ---
test warning
Continue? [y/n]: --- END ---

aContinue? [y/n]:  invalid input: a
sContinue? [y/n]:  invalid input: s
dContinue? [y/n]:  invalid input: d
fContinue? [y/n]:  invalid input: f
q
$

Alguém poderia por favor dizer por que funciona assim?

bash shell-script
  • 1 respostas
  • 77 Views
Martin Hope
DonJ
Asked: 2018-03-10 13:27:08 +0800 CST

filtro jq: mostra toda a estrutura com seleção

  • 1

Eu tenho o seguinte file1 json:

{
  "name": "eye",
  "attributes": [
    {
      "name": "Width",
      "value": "1920"
    },
    {
      "name": "Height",
      "value": "1080"
    },
    {
      "name": "WinKeyMapping",
      "value": "leftwin"
    }
  ],
  "starts": [
    {
      "name": "step1",
      "attributeList": [
        {
          "name": "Command",
          "value": "bash"
        },
        {
          "name": "Test",
          "value": "none"
        }
      ]
    }
  ]
}

e seguinte filtro:

$ jq '.starts[].attributeList[]|select(.name=="Command")' file1
{
  "name": "Command",
  "value": "bash"
}
$

como eu poderia obter toda a estrutura para esta seleção?

saída esperada:

{
  "starts": [
    {
      "attributeList": [
        {
          "name": "Command",
          "value": "bash"
        }
      ]
    }
  ]
}
json jq
  • 3 respostas
  • 2862 Views

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