Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

1

229
Visualizações
Print min and max with awk

Why wont this awk script work, where I want to print the min and max of an input by just reading the data once. I would also like to initialize the min and max variable with the first value of the data.

Say I have a file

a 14
a 34
a 234
a 2345
a 1
a 24

I am using awk to print the min and max with:

cat test.txt | awk 'BEGIN {min=$2; max=$2} {if ($2 < min) {min=$2}; if ($2 > max) {max=$2} } END {print "min: " min "max: " max}'

But I am getting a result of:

min: max: 2345

I dont understand why min is set to blank?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Hello! Now suppose I have a list with approx 8 columns. and I want to print the maximum and minimum of column 5 for example. How should I do?

about 4 years ago · MARCOS STRASOSIER Relatório

1

The BEGIN {} block is processed before the first line so $2 is undefined.

$ cat file
a 14
a 34
a 234
a 2345
a 1
a 24
$ awk 'NR == 1  { min = max = $2; next }
       $2 > max { max = $2 }
       $2 < min { min = $2 }
       END      { print "min: " min ", max: " max }' file
min: 1, max: 2345
over 4 years ago · Santiago Trujillo Relatório

1

All numeric values in awk are stored in floating-point format, and there are no equivalents to C INT_MIN, INT_MAX, so you simply need to pick the range of values you wish to handle and initialize your max to the minimum possible value in the range you wish to consider, and min to the maximum possible value in the range you wish to consider.

For signed integer values, simply choosing the min/max values for 32-bit a signed integer is reasonable. For example, you can do:

 awk '
  BEGIN { min=2147483647; max=-2147483648 } 
  $2 > max { max=$2 } 
  $2 < min { min=$2 }
  END { print "max: ", max ORS "min: ", min }
' file

Example Use/Output

With your data in file, you would get:

$ awk '
>   BEGIN { min=2147483647; max=-2147483648 }
>   $2 > max { max=$2 }
>   $2 < min { min=$2 }
>   END { print "max: ", max ORS "min: ", min }
> ' file
max:  2345
min:  1

Which is what you were looking for.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda