簡體   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