繁体   English   中英

bash脚本从文件中读取数字

[英]bash scripting reading numbers from a file

您好,我需要制作一个bash脚本,该脚本将从文件中读取,然后在文件中添加数字。 例如,即时通讯读取的文件为:

猫samplefile.txt

 1
 2
 3
 4

该脚本将使用文件名作为参数,然后将这些数字相加并打印出总和。 我对如何从文件中读取整数然后将其存储在变量中一事无成。 到目前为止,我有以下内容:

#! /bin/bash

file="$1"   #first arg is used for file
sum=0       #declaring sum
readnums    #declaring var to store read ints

if [! -e $file] ; do     #checking if files exists
    echo "$file does not exist"
    exit 0
fi

while read line ; do

do < $file

exit 

有什么问题? 您的代码看起来不错,但readnums不是有效的命令名称,并且在if条件中的方括号内需要空格。 (哦和"$file"应该正确地用双引号引起来。)

#!/bin/bash

file=$1
sum=0

if ! [ -e "$file" ] ; do     # spaces inside square brackets
    echo "$0: $file does not exist" >&2  # error message includes $0 and goes to stderr
    exit 1                   # exit code is non-zero for error
fi

while read line ; do
    sum=$((sum + "$line"))
do < "$file"


printf 'Sum is %d\n' "$sum"
# exit                       # not useful; script will exit anyway

但是,shell传统上并不是算术的很好工具。 也许尝试像

awk '{ sum += $1 } END { print "Sum is", sum }' "$file"

也许在shell脚本的片段中以检查文件是否存在,等等(尽管在这种情况下,您仍然会从Awk收到相当有用的错误消息)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM