问题:
[root@base tmp]# cat ent.txt
1
2
3
4
5
6
7
8
9
10
要求输出结果:1+2+3+4+5+6+7+8+9+10+=55
最好使用tr命令打印出
分析题后,想到最简单的解法就是循环拼接打印结果:
#!/bin/sh
NumArray=($(cat /tmp/ent.txt | awk '{print $1}'))
result="1"
all=1
for((i=1;i<${#NumArray[*]};i++))
do
result="$result+${NumArray[$i]}"
all=$((${NumArray[$i]}+$all))
done
echo $result=$all
看过老男孩老师的答案,才叫拜服,很是简单:
cat ent.txt | tr "\n" "+" | sed 's/\+$/\n/' 直接用tr将"\n"替换为"+",然后sed替换最后一个"+"
cat ent.txt |tr "\n" "+"|sed 's/\+$/\n/'|bc 一个|bc就可以将字符串表达式,转换成算术表达式
python实现:
# coding: utf-8
import sys
from itertools import groupby
def demo(ListFile):
reList = []
files = file(ListFile,'r')
lines = files.readlines()
str_list = "1"
result=0
for item in lines:
rLIst = item.replace("\n","")
reList.append(rLIst)
if int(rLIst) > 1:
str_list = str(str_list)+"+"+str(rLIst)
result = result + int(rLIst)
return "%s=%d" %(str_list,result)
if __name__ == "__main__":
print demo("/tmp/ent.txt")