0

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

3 Answers 3

2

If you want to use a while loop, you could say:

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

For your input, it'd emit:

4
9
16

As per your comment, 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
Sign up to request clarification or add additional context in comments.

1 Comment

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?
2

Try awk:

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

1 Comment

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

You don't need to use while loop. Using awk:

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

2 Comments

I would like to do it with a while loop. will it be possible with a while loop?
@anansharm, while read n; do bc <<< $n*$n ; done < read7 or while read n; do echo $((n*n)) ; done < read7 as devnull's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.