I have a file that contains words and numbers at random positions. I must write a shell script that adds all the numbers from the file.
I thought about something like this:
filename=$1
words=` echo $filename `
sum=0
for word in words;
do
#if $word is number, add to sum
done
How can I verify if something is a number in shell? Or this whole approach is wrong?
You can for exapmle use this:
grep -ow '[0-9]*' file | awk '{count+=$1} END{print count}'
grep -ow '[0-9]*' file
gets all the blocks of numbers of the file. -w
matches just words, so that a23b
won't be a match.awk '{count+=$1} END{print count}'
loops through the grep
result adding each one of the numbers to the count
variable. Finally, prints the result.$ cat a
aa b23 23 55
adf 23 23 62l
$ grep -ow '[0-9]*' a | awk '{count+=$1} END{print count}'
124
$ grep -ow '[0-9]*' a
23
55
23
23
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments