[英]Extracting numbers from file
I have a txt file " 80 50 65 100 2 35 1 " and i need to add each number in a Var or even better all of them in an array. 我有一个txt文件“ 80 50 65 100 2 35 1”,我需要将每个数字添加到Var中,甚至更好地将它们添加到数组中。 like ...
喜欢 ...
var1=80 var2=50 var1 = 80 var2 = 50
or 要么
array[0]=80 数组[0] = 80
.by the way the number after that must be functional . 顺便说一句,后面的数字必须可以使用。 I mean i need to be able to sum= $var1 +$var2 for example.
我的意思是我需要能够求和=例如$ var1 + $ var2。 Is there a way to do that ?
有没有办法做到这一点 ? Thank you!!
谢谢!!
If your numbers are all on a line, use read
如果您的电话号码全都在线,请使用
read
read -a array < numbers.txt
If they're on multiple lines you can change the end of line delimiter like this 如果它们在多行上,则可以像这样更改行尾定界符
read -d'\0' -a array < numbers.txt
And now you have an array 现在你有了一个数组
printf 'Number: %s\n' "${array[@]}"
Oh yeah, and summing. 哦,是的,总结一下。 Lots of ways once you have an array, but how about
一旦有了数组,有很多方法,但是如何
printf '%s + ' "${array[@]}" | xargs -I{} echo {} 0 | bc
Or do it all in one process 或一站式完成
for n in "${array[@]}" ; do let sum+=$n ; done ; echo $sum
In bash, you can say 用bash可以说
array=( $(< numbers.txt) )
sum=$( IFS=+; echo "${array[*]}" | bc )
So if you have a file nums.dat
like 因此,如果您有
nums.dat
这样的文件
80 50 65 100 2 35 1
You can read these into an array with 您可以将它们读入数组
read -a MYARRAY < nums.dat
If you have a much older bash
or even ksh
then it was something like (can't remember exactly sorry) 如果您的
bash
甚至是ksh
都比较老,那么它就像(不记得完全对不起)
set -A MYARRAY $(cat nums.dat)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.