你好,我需要制作一个 bash 脚本,该脚本将从文件中读取,然后将数字添加到文件中。例如,我正在阅读的文件将读作:
猫样本文件.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 得到一个相当有用的错误消息)。
关于linux - bash脚本从文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28804172/