简体   繁体   English

bash脚本从文件中读取数字

[英]bash scripting reading numbers from a file

Hello i need to make a bash script that will read from a file and then add the numbers in the file. 您好,我需要制作一个bash脚本,该脚本将从文件中读取,然后在文件中添加数字。 For example, the file im reading would read as: 例如,即时通讯读取的文件为:

cat samplefile.txt 猫samplefile.txt

 1
 2
 3
 4

The script will use the file name as an argument and then add those numbers and print out the sum. 该脚本将使用文件名作为参数,然后将这些数字相加并打印出总和。 Im stuck on how i would go about reading the integers from the file and then storing them in a variable. 我对如何从文件中读取整数然后将其存储在变量中一事无成。 So far what i have is the following: 到目前为止,我有以下内容:

#! /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 

What's the problem? 有什么问题? Your code looks fine, except readnums is not a valid command name, and you need spaces inside the square brackets in the if condition. 您的代码看起来不错,但readnums不是有效的命令名称,并且在if条件中的方括号内需要空格。 (Oh and "$file" should properly be inside double quotes.) (哦和"$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

However, the shell is not traditionally a very good tool for arithmetic. 但是,shell传统上并不是算术的很好工具。 Maybe try something like 也许尝试像

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

perhaps inside a snippet of shell script to check that the file exists, etc (though you'll get a reasonably useful error message from Awk in that case anyway). 也许在shell脚本的片段中以检查文件是否存在,等等(尽管在这种情况下,您仍然会从Awk收到相当有用的错误消息)。

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

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