当前位置:网站首页>Use shell to calculate the sum of numbers in text

Use shell to calculate the sum of numbers in text

2022-07-27 07:25:00 hawanglc

    A strange thing happened today : use wc -l *.txt > wc.out In the file of , The last line is not the sum of the records of all the files counted . In this case , I still need to write a shell Script , Let's add up wc.out The sum of the numbers of each record in the document .
    The following is the corresponding script ,shell The parameter of is file name , Here is wc.out.wc.out The file format is 『 Numbers file name 』.
    The main idea is : Read every line in the file , And then use cut command , Get the number in each line , Then add up this number .

#!/bin/bash

if [ $# -ne 1 ]
then
    echo "need one parameter: file_name needed"
    exit
fi

sum=0;
while read line; do amount=`echo $line|cut -d " " -f1`; sum=$(( ${amount} + $sum )) ;  done < $1;
echo "total amount is $sum"

 

原网站

版权声明
本文为[hawanglc]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/208/202207270610230392.html