Home COMSC-171 <- Prev Next ->

add script examples

These scripts add numbers (one per line) from standard input.

usage

Add numbers from keyboard:

path/to/executable 6 7 8 Ctrl+d

Add numbers piped from another command:

ls -ld * # long listing ls -ld * | tr -s ' ' # reduce consecutive runs of spaces to a single space ls -ld * | tr -s ' ' | cut -d ' ' -f 5 # output only size field ls -ld * | tr -s ' ' | cut -d ' ' -f 5 | path/to/executable # add sizes

bash

Sum=0 # initialize accumulator while read Num ; do # loop while input exists assigning each line to Num Sum=$(( $Sum + $Num )) # add input number to Sum done # end of while block echo $Sum # print total

scheme

(define (sum in-list) ; function with 1 list arg (let ((value (read))) ; local var, scheme object from STDIN (if (eof-object? value) ; if end of file (begin ; group statements (display (apply + in-list)) ; add list elements, print (newline)) ; print newline (sum (cons value in-list))))) ; construct new list, recursive call (sum '()) ; call function with empty list

awk

{ Sum += $1 } # integer accumulator + 1st field of each input line # no loop, input read automatically # no initialization, new variables default to zero END { print Sum } # END matches after last input line

perl

use strict ; # enable error checking use warnings ; # enable more error checking my $Sum = 0 ; # initialize accumulator (scaler, local scope) $Sum += $_ for <STDIN> ; # one-line foreach loop # < > is file read operator # $_ is default loop variable, add to accumulator print "$Sum\n" ; # explicit newline

tcl

set Sum 0 # initialize accumulator foreach Num [read stdin] {incr Sum $Num} # read STDIN, assign each line to Num, # add Num to Sum puts $Sum # print # alternate method set Nums [split [read -nonewline stdin] \n] # read STDIN, split on NL to list, # assign to Nums puts [tcl::mathop::+ {*}$Nums] # expand list, sum, print

python

import sys # use sys module Sum = 0 # initialize accumulator for Num in sys.stdin : # loop over lines from STDIN Sum += int(Num) # convert strings to integers, add to accumulator # block defined by indentation print Sum # print

lua

Sum = 0 -- initialize accumulator for Num in io.lines() do Sum = Sum + Num end -- loop over lines from STDIN -- add numeric value to Sum print(math.floor(Sum)) -- convert default float to int

php

<?php // opening HTML tag $str = file_get_contents("php://stdin") ; // read stdin to string $arr = explode("\n", $str) ; // split string to array on newlines echo array_sum($arr) . "\n" ; // sum array elements, print ?> // closing HTML tag

javascript

const fs = require("fs") // file handle for stdin const numarr = fs.readFileSync(0, "utf-8").split("\n") // read, split to array // convert strings to integers, reduce with summing function, print console.log(numarr.reduce((acc, val) => {return acc + Number(val)}, 0))

ruby

# read lines, convert strings to integers, reduce with summing function, print puts STDIN.reduce {|sum, num| sum.to_i + num.to_i }

scala

import io.Source // contains stdin // read stdin, make it a string, split on newlines, convert to list, // change strings to integers, add them up, print println(Source.stdin.mkString.split("[\n]+").toList.map(x => x.toInt).sum)

clojure

(println ; output with newline (reduce + ; sum elements of list (map #(Integer/parseInt %) ; strings to integers (Java method) (line-seq ; returns sequence (java.io.BufferedReader. *in*))))) ; read STDIN (Java method)

elixir

String.split(IO.read(:stdio, :all)) # read STDIN, split into list |> Enum.map(fn x -> String.to_integer(x) end) # convert strings to integers |> Enum.reduce(fn x, acc -> x + acc end) # add integers together |> IO.puts # print

julia

sum = 0 # initialize accumulator for num in eachline(stdin) # loop over all input lines global sum += parse(Int64, num) # convert to integer, add to accumulator end # end of for loop println(sum) # output with newline # alternate method # read bytes, convert to string, split to vector on newlines numvec = split(String(read(stdin)), r"\n") numvec[end] = "0" # change ending null string to a zero println(sum(parse.(Int64, numvec))) # convert strings to integers, add, print