我有一个数组文件,我需要对元素进行数学运算。我需要做的操作是将元素与其本身相乘,然后打印它。
输入看起来像这样:
1: 6.1703
44 -0.27135
46 0.30270
44 0.52648
2: 6.1932
44 0.51448
46 0.14674
44 0.27957
46 -0.31834
3: 6.5664
45 -0.11892
45 0.66483
46 0.12505
每个数组的第一行是标题。需要对第二列的元素进行数学运算。
输出需要是:
1: 6.1703
44 0.07363
46 0.09162
44 0.27718
2: 6.1932
44 0.26468
46 0.02153
44 0.07815
46 0.10134
3: 6.5664
45 0.0141
45 0.44199
46 0.01563
有什么想法或建议吗?
答案1
我会用来awk
这样做:
awk '$1 ~ /^[0-9]+$/ {$2*=$2}; 1'
如果第一列是数字,则将第二列与其自身相乘。然后打印整行。
答案2
while read line; do # for all lines in the file
i=0 # initialise loop counter
for param in $line; do # for all words on the line
if [[ $i -ne 0 ]]; then # if its not the first one
echo $param | awk '{printf "%4.3f\n",$1*$1}' # print the result of squaring
fi # (you could output to a file with >>)
((i++)) # increment loop counter
done
done < yourfilename # stream in your file