编写 shell 脚本对文本中无序的一列数字排序,并计算之和。
例如:
root@nianyu-virtual-machine:/mnt# cat num.txt
3
9
6
5
4
7
8
6
4
3
1
方法一:
#!/bin/bash
sum=0
for line in $(sort -n num.txt);do
echo "$line"
sum=$((sum+line))
done
echo "sum=$sum"
使用while read -r line
优化:
#!/bin/bash
sum=0
sort -n num.txt -o num.txt
while read -r line;do
echo "$line"
sum=$((sum+line))
done < "num.txt"
echo "sum=$sum"
方法二:
#!/bin/bash
sort -n num.txt | awk '{a+=$0;print $0}END{print "SUM="a}'
网友评论