示例文本文件包含:
04/06/1991 06/05/2001 06/08/2015
cat ".sort.txt" | while IFS='/' read -r num inta intb intc;do
for i in "${ADDR[@]}";do
s=$inta+$intb+$intc
echo $s >> .sort.txt
done
done <<< "$IN"
期望文本文件变为:
04/06/1991 06/05/2001 06/08/2015 2001 2012 2029
答案 0 :(得分:2)
Perl救援:
echo '04/06/1991 06/05/2001 06/08/2015' \
| perl -MList::Util=sum -lane '$_ = sum split m(/) for @F; print "$_ @F"'
-a
填充@F数组。-n
逐行处理输入。/
上分开,数字相加。然后,打印原始行($_
)并附加新值。请注意,它适用于每行的任意数量的日期。
答案 1 :(得分:1)
使用bash:
while IFS=" /" read -r a1 a2 a3 b1 b2 b3 c1 c2 c3; do
echo $a1/$a2/$a3 $b1/$b2/$b3 $c1/$c2/$c3 $((${a1#0}+${a2#0}+$a3)) $((${b1#0}+${b2#0}+$b3)) $((${c1#0}+${c2#0}+$c3))
done < sort.txt
输出:
04/06/1991 06/05/2001 06/08/2015 2001 2012 2029
答案 2 :(得分:0)
使用awk很容易:
awk '{printf $0 OFS; for (i=1; i<=NF; i++) { split($i, arr, "/");
printf "%s%s", (arr[1]+arr[2]+arr[3]), (i<NF)?OFS:RS}}' .sort.txt
04/06/1991 06/05/2001 06/08/2015 2001 2012 2029