linux - bash脚本从文件中读取数字

标签 linux bash while-loop

你好,我需要制作一个 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/

相关文章:

c++ - vim 或 gcc 无法解释的行为

bash - bash 中的套管箭头键

bash - "-ne"在 bash 中是什么意思?

python -> time a while 循环一直在运行

linux - Linux服务器中的文件如何按名称分类?

c++ - 如何在 cout 上使用 isatty(),或者我可以假设 cout == 文件描述符 1?

c - 使用哪个循环?

c - 用 C 语言模拟钟摆

linux - 使用 linux shell 命令将多行输出合并为一行重新格式化报告文件

linux - 使用 bash 脚本创建文件夹和文件