Leer elementos del archivo usando el script bash

If I have a file with name "read7" with a list of numbers in it, for example:

2
3
4

How can I write a bash script with a while loop to read all the elements in the file and square the numbers and send it as a standard output?

So, after running the script we should get an output of

4
9
16

preguntado el 02 de diciembre de 13 a las 08:12

3 Respuestas

Si quieres usar un while loop, you could say:

while read -r i; do echo $((i*i)); done < read7

For your input, it'd emit:

4
9
16

Según tu comentario, if the file has words and numbers in it. How do I make it read just the numbers from the file?. You could say:

while read -r i; do [[ $i == [0-9]* ]] && echo $((i*i)); done < read7

For an input file containing:

2
foo
3
4

it'd produce:

4
9
16

contestado el 23 de mayo de 17 a las 12:05

I missed out a point in my question, if the file has words and numbers in it. How do I make it read just the numbers from the file? - anansharm

Prueba awk:

awk '{print $1*$1}' read7

Respondido el 02 de diciembre de 13 a las 08:12

yeah, however, I would like to do it with a while loop. will it be possible with a while loop? - anansharm

No necesitas usar while círculo. Utilizando awk:

$ cat read7
2
3
4
$ awk '{print $1*$1}' read7
4
9
16

Respondido el 02 de diciembre de 13 a las 08:12

I would like to do it with a while loop. will it be possible with a while loop? - anansharm

@anansharm, while read n; do bc <<< $n*$n ; done < read7 or while read n; do echo $((n*n)) ; done < read7 as devnull's answer. - falsedad

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.