从文件和标准输入中添加数字 [英] Add numbers from file and standard input

查看:74
本文介绍了从文件和标准输入中添加数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用whilefor循环在壳内将数字加在一起?

How do I add numbers together inside the shell using a while or for loop?

我只想要一个能够与标准输入和文件一起使用的非常简单的程序.

I just want a really simple program that works with standard input and files.

示例:

$ echo 1 2 | sh myprogram
3

如果文件myfile包含数字列表,我希望能够做到这一点:

And if a file myfile contains a list of numbers, I want to be able to do this:

sh myprogram myfile

并获得数字的总和作为输出.

and get the sum of the numbers as output.

推荐答案

此问题在其核心处是链接问题的副本,但它确实声明了其他要求 (是否全部由OP完全使用):

While this question is at its core a duplicate of the linked question, it does state additional requirements (whether they were all fully intended by the OP or not):

  • 解决方案应打包为 script .

解决方案应符合POSIX(问题通常被标记为)

The solution should be POSIX-compliant (question is generically tagged shell)

输入应来自文件(如果已指定)或默认情况下来自stdin.

Input should either come from a file, if specified, or from stdin by default.

单个输入行(例如,echo 1 2)上的可以是多个数字.

There can be multiple numbers on a single input line (e.g., echo 1 2).

解决方案应使用whilefor循环,即纯外壳解决方案.

The solution should use a while or for loop, i.e. a pure shell solution.

下面的解决方案满足了这些要求,除了最后一个要求 ,这可能是OP的交易突破口,但也许其他人会发现它很有用.

The solution below addresses these requirements, except for the last one - which may well be a deal-breaker for the OP, but perhaps others will find it useful.

通过使用外部实用程序偏离该要求,这意味着解决方案在大量输入数据中表现良好-Shell代码中的循环很慢.

Deviating from that requirement by using external utilities means the solution will perform well with large sets of input data - loops in shell code are slow.

如果仍然需要shell while循环解决方案,请参见本文的底部;它还包括输入验证.

If you still want a shell while-loop solution, see the bottom of this post; it also includes input validation.

myprogram 的内容(符合POSIX,但需要一个文件系统,该文件系统将标准输入表示为/dev/stdin):

请注意,将执行 no 输入验证-输入中的所有令牌均假定为十进制数字(正数或负数);该脚本将与其他任何输入一起中断.请参阅下面的-一种更复杂的解决方案-过滤掉非十进制数字的令牌.

Note that no input validation is performed - all tokens in the input are assumed to be decimal numbers (positive or negative); the script will break with any other input. See below for a - more complex - solution that filters out non-decimal-number tokens.

#!/bin/sh

{ tr -s ' \t\n' '+'; printf '0\n'; } < "${1-/dev/stdin}" | bc

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆