anansharm
anansharm

Reputation: 193

Read Elements from file using bash script

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

Upvotes: 0

Views: 891

Answers (3)

devnull
devnull

Reputation: 123688

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

Upvotes: 2

falsetru
falsetru

Reputation: 369474

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

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

Upvotes: 2

vahid abdi
vahid abdi

Reputation: 10318

Try awk:

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

Upvotes: 2

Related Questions