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-38638

TomRoche's questions

Martin Hope
TomRoche
Asked: 2020-01-15 21:43:34 +0800 CST

nova década: como dizer algo como `find /path/ -name 'file.20{19,20}*'` (mas que funciona)

  • 3

resumo:

  1. Um determinado sistema tem muitos arquivos de texto com nomes ~= [type of file].[8-digit date].
  2. Para pesquisar esses arquivos, eu gosto (e quero manter) usando este idioma: find /path/ -name 'file.nnnn*' -print | xargs -e fgrep -nH -e 'text I seek'(onde nnnn== ano de 4 dígitos)
  3. ... e na última década também fiz findglob ao longo de anos comofind /path/ -name 'file.201[89]*' -print | xargs ...
  4. ... mas agora não posso fazer findglob em 2019 e 2020 comfind /path/ -name 'file.20{19,20}*' -print | xargs ...
  5. ... embora esse "globbing de chaves" (termo correto?) funcione bem com ls!

Existe uma maneira {concisa, elegante} de dizer findo que eu quero, sem fazer a pós- findlimpeza (ou seja, o que estou fazendo agora) à la

find /path/ -name 'file.*' -print | grep -e '\.2019\|\.2020' | xargs ...

? FWIW, prefiro uma solução que funcione com xargs.

detalhes:

Trabalho em um sistema com muitas convenções que me precedem há muito tempo e que não posso mudar. Uma delas é que tem muitos arquivos de texto com nomes ~= [type of file].[8-digit date], por exemplo, woohoo_log.20191230. Ao pesquisar nesses arquivos por algum texto, normalmente (como em, quase sempre) uso o find ... grepidioma (geralmente usando Emacs' M-x find-grep). (FWIW, este é um sistema Linux com

$ find --version
find (GNU findutils) 4.4.2
...
$ bash --version
GNU bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu)

e atualmente não tenho status para alterar qualquer um deles, se eu quisesse.) Muitas vezes, conheço o intervalo de anos do assunto em questão e, portanto, tentarei restringir o que findretorna (para acelerar o processamento), com (por exemplo)

find /path/ -type f -name 'file.nnnn*' -print | xargs -e fgrep -nH -e 'text I seek'

onde nnnn== ano de 4 dígitos. Este WFM, e eu gosto (e quero continuar) usando o idioma acima ... especialmente porque também posso usá-lo para pesquisar anos como

find /path/ -type f -name 'file.201[89]*' -print | xargs ...

Mas esta nova década parece estar quebrando esse idioma, e (para mim pelo menos) de forma mais estranha. (Eu não estava aqui quando a última década mudou.) Suponha que eu escolha um texto que sei que está em um arquivo de 2019 && um arquivo de 2020 (como em, posso abrir os arquivos e ver o texto). Se eu atualmente faço

find /path/ -name 'file.20{19,20}*' -print | xargs ...

greptermina inesperadamente/irritantemente with no matches found, porque

$ find /path/ -name 'file.20{19,20}*' -print | wc -l
0

Mas se eu fizer

find /path/ -type f -name 'file.*' -print | grep -e '\.2019\|\.2020' | xargs ...

grepretorna os resultados esperados. O que é bom, mas ... ummm ... isso é apenas feio, especialmente desde que este "glob de chaves" (por favor, corrija-me se este uso estiver incorreto ou obsoleto) funciona a partir de ls! Ou seja, isso me mostra os arquivos no intervalo de ano relevante (ou seja, 2019..2020)

ls -al /path/file.20{19,20}*

Por isso gostaria de saber:

  1. Não estou dando findo glob certo para este caso de uso? O que eu preciso dizer findpara fazê-lo fazer o que lsestá fazendo corretamente/capazmente?
  2. Isso é um problema com xargs? Se sim, posso viver com uma find ... -execsolução, mas... meu cérebro funciona melhor com xargso , então prefiro ficar com isso se possível. (Me chame de débil mental, mas -execa sintaxe de faz meu cérebro doer .)
find wildcards
  • 3 respostas
  • 774 Views
Martin Hope
TomRoche
Asked: 2019-06-17 23:37:12 +0800 CST

instrução bash `case` para classificar a entrada como não e inteiros

  • 3

resumo: eu gostaria de usar uma bash casedeclaração (em outro código) para classificar as entradas para saber se elas são

  • um número inteiro positivo
  • um número inteiro negativo
  • zero
  • uma string vazia
  • uma string não inteira

Segue o código executável, que está classificando corretamente as seguintes entradas:

  • ''
  • word
  • a\nmultiline\nstring
  • 2.1
  • -3

mas está classificando ambos os itens a seguir como ... inteiros negativos:-(

  • 0
  • 42

detalhes:

Salve o seguinte em um arquivo (por exemplo /tmp/integer_case_statement.sh, ) chmod, e execute-o:

#!/usr/bin/env bash

### This should be a simple `bash` `case` statement to classify inputs as
### {positive|negative|zero|non-} integers.
### Trying extglob, since my previous integer-match patterns failed.
### Gotta turn that on before *function definition* per https://stackoverflow.com/a/34913651/915044
shopt -s extglob

declare cmd=''

function identify() {
    local -r it=${1}  # no quotes in case it's multiline
#    shopt -s extglob # can't do that here
    case ${it} in
        '')
            # empty string, no need for `if [[ -z ...`
            >&2 echo 'ERROR: null arg'
            ;;
        ?(-|+)+([[:digit:]]))
            # it's an integer, so just say so and fallthrough
            >&2 echo 'DEBUG: int(it), fallthrough'
            ;&
        -+([[:digit:]]))
            # it's negative: just return it
            >&2 echo 'DEBUG: int(it) && (it < 0), returning it'
            echo "${it}"
            ;;
        0)
            # it's zero: that's OK
            >&2 echo 'DEBUG: int(it) && (it == 0), returning it'
            echo '0'
            ;;
        ++([[:digit:]]))
            # it's positive: just return it
            >&2 echo 'DEBUG: int(it) && (it > 0), returning it'
            echo "${it}"
            ;;
        *)
            # not an integer, just return it
            >&2 echo 'DEBUG: !int(it)'
            echo "${it}"
            ;;
    esac
} # end function identify

echo -e "'bash --version'==${BASH_VERSION}\n"

echo "identify '':"
identify ''
echo
# > ERROR: null arg

echo 'identify word:'
identify word
echo
# > DEBUG: !int(it)
# > word

echo 'identify a
multiline
string:'
identify 'a
multiline
string'
echo
# > DEBUG: !int(it)
# > a
# > multiline
# > string

echo 'identify 2.1:'
identify 2.1
echo
# > DEBUG: !int(it)
# > 2.1

echo 'identify -3:'
identify -3
echo
# > DEBUG: int(it), fallthrough
# > DEBUG: int(it) && (it < 0), returning it
# > -3

echo 'identify 0:'
identify 0
echo
# > DEBUG: int(it), fallthrough
# > DEBUG: int(it) && (it < 0), returning it
# > 0

echo 'identify 42:'
identify 42
echo
# > DEBUG: int(it), fallthrough
# > DEBUG: int(it) && (it < 0), returning it
# > 42

exit 0

A saída atual está embutida no arquivo, mas para facilitar a leitura, aqui está minha saída atual separadamente:

'bash --version'==4.3.30(1)-release

identify '':
ERROR: null arg

identify word:
DEBUG: !int(it)
word

identify a
multiline
string:
DEBUG: !int(it)
a
multiline
string

identify 2.1:
DEBUG: !int(it)
2.1

identify -3:
DEBUG: int(it), fallthrough
DEBUG: int(it) && (it < 0), returning it
-3

identify 0:
DEBUG: int(it), fallthrough
DEBUG: int(it) && (it < 0), returning it
0

identify 42:
DEBUG: int(it), fallthrough
DEBUG: int(it) && (it < 0), returning it
42

As últimas 2 entradas são o meu problema: por que a instrução case está identificando

  • 0 como um número inteiro negativo (em vez de 0)
  • 42 como um número inteiro negativo (em vez de positivo)

? Sua ajuda é apreciada.

bash wildcards
  • 1 respostas
  • 1378 Views
Martin Hope
TomRoche
Asked: 2018-02-07 16:17:40 +0800 CST

`declare` sem causar problemas com funções/comandos ausentes?

  • -5

resumo: Se basheu tentar atribuir a saída de uma função ausente a uma declarevariável previamente d (ou seja, não {constante, somente leitura}), posso detectar a falha com testes "normais". Mas se eu tentar atribuir a saída de uma função ausente a uma variável enquanto a estiver declaredigitando (por exemplo, para tornar a variável {constante, somente leitura}), não apenas a atribuição não falhará com testes "normais", como também não falha de força com builtins "normais". Como posso fazer o último caso falhar?

detalhes:

Recentemente, encontrei um problema em um bashscript muito maior, que tentei destilar nos 2 scripts a seguir. Basicamente, estou meio que fazendo TDD com bash( snark > /dev/null), então entre outras coisas

  • Quero que os comandos/funções ausentes falhem rapidamente
  • Eu quero evitar reescrever constantes

No entanto, bashparece estar me permitindo atribuir a saída de uma função ausente a uma variável enquanto declarevar. Por exemplo, o seguinte script (salvo como /path/to/assign_at_declare.sh) ...

#!/usr/bin/env bash

function foo() {
    return 0
}

# function bar() {}               # does not exist!

declare ret_val=''
declare -r MESSAGE_PREFIX="$(basename "${BASH_SOURCE}"):"
declare -r ERROR_PREFIX="${MESSAGE_PREFIX} ERROR:"

echo -e "\n${MESSAGE_PREFIX} a naïve 1st attempt:\n"

declare -ir FOO1_VAL="$(foo)"   # this should succeed, and does
ret_val="${?}"
if   [[ "${ret_val}" -ne 0  ]] ; then
    >&2 echo "${ERROR_PREFIX} foo returned '${ret_val}', exiting ..."
    exit 3
elif [[ -z "${FOO1_VAL}"  ]] ; then
    >&2 echo "${ERROR_PREFIX} foo returned null, exiting ..."
    exit 4
else
    echo "${MESSAGE_PREFIX} FOO1_VAL='${FOO1_VAL}'"
fi

declare -ir BAR1_VAL="$(bar)"   # this should fail ... but doesn't
ret_val="${?}"
if   [[ "${ret_val}" -ne 0  ]] ; then
    >&2 echo "${ERROR_PREFIX} bar returned '${ret_val}', exiting ..."
    exit 5
elif [[ -z "${BAR1_VAL}"  ]] ; then
    >&2 echo "${ERROR_PREFIX} bar returned null, exiting ..."
    exit 6
else
    echo "${MESSAGE_PREFIX} BAR1_VAL='${BAR1_VAL}'"
fi

echo -e "\n${MESSAGE_PREFIX} get tough using \`set\` builtins:\n"
# see https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
set -o errexit
set -o pipefail

declare -ir FOO2_VAL="$(foo)"   # this should succeed, and does
ret_val="${?}"
if   [[ "${ret_val}" -ne 0  ]] ; then
    >&2 echo "${ERROR_PREFIX} foo returned '${ret_val}', exiting ..."
    exit 3
elif [[ -z "${FOO2_VAL}"  ]] ; then
    >&2 echo "${ERROR_PREFIX} foo returned null, exiting ..."
    exit 4
else
    echo "${MESSAGE_PREFIX} FOO2_VAL='${FOO2_VAL}'"
fi

declare -ir BAR2_VAL="$(bar)"   # this should fail ... but doesn't
ret_val="${?}"
if   [[ "${ret_val}" -ne 0  ]] ; then
    >&2 echo "${ERROR_PREFIX} bar returned '${ret_val}', exiting ..."
    exit 5
elif [[ -z "${BAR2_VAL}"  ]] ; then
    >&2 echo "${ERROR_PREFIX} bar returned null, exiting ..."
    exit 6
else
    echo "${MESSAGE_PREFIX} BAR2_VAL='${BAR2_VAL}'"
fi

exit 0

... produz a seguinte saída:

assign_at_declare.sh: a naïve 1st attempt:

assign_at_declare.sh: FOO1_VAL='0'
/path/to/assign_at_declare.sh: line 27: bar: command not found
assign_at_declare.sh: BAR1_VAL='0'

assign_at_declare.sh: get tough using `set` builtins:

assign_at_declare.sh: FOO2_VAL='0'
/path/to/assign_at_declare.sh: line 56: bar: command not found
assign_at_declare.sh: BAR2_VAL='0'

Isso parece estranho, pois não observo esse comportamento se tento atribuir a saída da função ausente a uma variável após declare ing a var (ou seja, se a var não for {constant, read-only}) como no script a seguir (salvo como /path/to/assign_after_declare.sh) ...

#!/usr/bin/env bash

function foo() {
    return 0
}

# function bar() {}           # does not exist!

declare ret_val=''
declare -i foo_val=0
declare -i bar_val=0
declare -r MESSAGE_PREFIX="$(basename "${BASH_SOURCE}"):"
declare -r ERROR_PREFIX="${MESSAGE_PREFIX} ERROR:"

echo -e "\n${MESSAGE_PREFIX} following works as expected\n"

foo_val="$(foo)"           # this should succeed, and does with/out `declare`
ret_val="${?}"
if   [[ "${ret_val}" -ne 0  ]] ; then
    >&2 echo "${ERROR_PREFIX} foo returned '${ret_val}', exiting ..."
    exit 3
elif [[ -z "${foo_val}"  ]] ; then
    >&2 echo "${ERROR_PREFIX} foo returned null, exiting ..."
    exit 4
else
    echo "${MESSAGE_PREFIX} foo_val='${foo_val}'"
fi

bar_val="$(bar)"           # this succeeds with `declare`, fails without
ret_val="${?}"
if   [[ "${ret_val}" -ne 0  ]] ; then
    >&2 echo "${ERROR_PREFIX} bar returned '${ret_val}', exiting ..."
    exit 5
elif [[ -z "${bar_val}"  ]] ; then
    >&2 echo "${ERROR_PREFIX} bar returned null, exiting ..."
    exit 6
else
    echo "${MESSAGE_PREFIX} bar_val='${bar_val}'"
fi

exit 0

... que produz a seguinte saída:

assign_after_declare.sh: following works as expected

assign_after_declare.sh: foo_val='0'
/path/to/assign_after_declare.sh: line 29: bar: command not found
assign_after_declare.sh: ERROR: bar returned '127', exiting ...

Existe uma maneira de forçar basha falha rápida ao atribuir durante um declare? Se sim, aguardo sua resposta.

Alternativamente, está bashtrabalhando como projetado? Em caso afirmativo, faça um link para uma referência; Tentei pesquisar esta pergunta, mas meus seletores estavam incorretos ou retornaram tantas respostas não relacionadas que foram inúteis.

bash shell-builtin
  • 1 respostas
  • 133 Views
Martin Hope
TomRoche
Asked: 2017-11-29 20:02:29 +0800 CST

resultados inesperados de `service | grep`

  • 0
$ sudo service --status-all | fgrep -e 'bluetooth'
 [ ? ]  alsa-utils
 [ ? ]  binfmt-support
 [ + ]  bluetooth
 [ ? ]  cpufrequtils
 [ ? ]  cryptdisks
 [ ? ]  cryptdisks-early
 [ ? ]  hdparm
 [ ? ]  hwclock.sh
 [ ? ]  kmod
 [ ? ]  loadcpufreq
 [ ? ]  networking
 [ ? ]  plymouth
 [ ? ]  plymouth-log
 [ ? ]  pppd-dns
 [ ? ]  udev-finish
 [ ? ]  virtualbox-guest-x11
$ sudo service bluetooth stop
[ ok ] Stopping bluetooth: /usr/sbin/bluetoothd.
$ sudo service --status-all | fgrep -e 'bluetooth'
 [ ? ]  alsa-utils
 [ ? ]  binfmt-support
 [ - ]  bluetooth
 [ ? ]  cpufrequtils
 [ ? ]  cryptdisks
 [ ? ]  cryptdisks-early
 [ ? ]  hdparm
 [ ? ]  hwclock.sh
 [ ? ]  kmod
 [ ? ]  loadcpufreq
 [ ? ]  networking
 [ ? ]  plymouth
 [ ? ]  plymouth-log
 [ ? ]  pppd-dns
 [ ? ]  udev-finish
 [ ? ]  virtualbox-guest-x11

Por que estou obtendo mais de 1 linha de saída service | grepquando apenas 1 linha (em cada conjunto de saída) corresponde ao greppadrão? Existe algo (ruim) mágico no início das linhas [?]? Alternativamente, o que estou perdendo?

FWIW, estou correndo

$ date
Tue Nov 28 20:51:46 MST 2017
$ uname -rsv
Linux 3.16.0-4-amd64 #1 SMP Debian 3.16.43-2+deb8u5 (2017-09-19)
$ lsb_release -ds
LMDE 2 Betsy
$ cat /etc/debian_version
8.9
$ gcc --version | head -n 1
gcc (Debian 4.9.2-10) 4.9.2
grep services
  • 1 respostas
  • 93 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