Read Multiple Numbers in Shell Scripting Then Print the Sum of All the Numbers

This section presents several beat script examples.

Hello World

Case nine. Hi World

              #!/bin/sh echo "Hello world"            

Using Arguments

Case 10. Beat out Script Arguments

              #!/bin/bash  # example of using arguments to a script echo "My first proper noun is $1" echo "My surname is $two" echo "Total number of arguments is $#"            

Save this file as name.sh, fix execute permission on that file by typing chmod a+x name.sh and then execute the file like this: ./proper name.sh.

            $ chmod a+x name.sh $ ./name.sh Hans-Wolfgang Loidl My get-go name is Hans-Wolfgang My surname is Loidl Full number of arguments is 2          

Version 1: Line count case

The beginning instance simply counts the number of lines in an input file. It does then by iterating over all lines of a file using a while loop, performing a read performance in the loop header. While there is a line to process, the loop body will be executed in this case only increasing a counter by ((counter++)). Additionally the current line is written into a file, whose name is specified by the variable file, by echoing the value of the variable line and redirecting the standard output of the variable to $file. the current line to file. The latter is not needed for the line count, of course, just demonstrates how to check for success of an operation: the special variable $? will contain the return code from the previous command (the redirected repeat). By Unix convention, success is indicated by a return code of 0, all other values are fault lawmaking with application specific significant.

Another important effect to consider is that the integer variable, over which iteration is performed should e'er count down so that the analysis can find a bound. This might require some restructuring of the code, as in the post-obit example, where an explicit counter z is introduced for this purpose. Later on the loop, the line count and the contents of the last line are printed, using echo. Of course, there is a Linux command that already implements line-count functionality: wc (for word-count) prints, when called with pick -fifty, the number of lines in the file. We apply this to bank check wether our line count is correct, demonstrating numeric operations on the manner.

            #!/bin/fustigate # Simple line count example, using fustigate # # Fustigate tutorial: http://linuxconfig.org/Bash_scripting_Tutorial#eight-two-read-file-into-bash-assortment # My scripting link: http://www.macs.hw.air-conditioning.uk/~hwloidl/docs/index.html#scripting # # Usage: ./line_count.sh file # -----------------------------------------------------------------------------  # Link filedescriptor 10 with stdin exec 10<&0 # stdin replaced with a file supplied every bit a first statement exec < $ane # call up the name of the input file in=$i  # init file="current_line.txt" let count=0  # this while loop iterates over all lines of the file while read LINE do     # increase line counter      ((count++))     # write current line to a tmp file with name $file (non needed for counting)     echo $LINE > $file     # this checks the return code of echo (not needed for writing; just for demo)     if [ $? -ne 0 ]       then echo "Error in writing to file ${file}; cheque its permissions!"     fi washed  echo "Number of lines: $count" repeat "The concluding line of the file is: `cat ${file}`"  # Note: You can accomplish the aforementioned by but using the tool wc like this repeat "Expected number of lines: `wc -l $in`"  # restore stdin from filedescriptor 10 # and close filedescriptor ten exec 0<&10 10<&-          

As documented at the kickoff of the script, it is called like this (you must have a file text_file.txt in your current directory):

            $            ./line_count.sh text_file.txt          
Note Sample text file

You can go a sizable sample text file by typing:

                      $                      cp /home/msc/public/LinuxIntro/WaD.txt text_file.txt                    

Several versions of line counting beyond a prepare of files

This department develops several shell scripts, each counting the total number of lines across a prepare of files. These examples elaborate specific shell features. For counting the number of lines in one file nosotros use wc -l. Equally a simple exercise you can replace this command with a call to the line counting script above.

Version 1: Explicit For loop

We use a for-loop to iterate over all files provided as arguments to the script. We can access all arguments through the variable $*. The sed control matches the line count, and replaces the entire line with just the line count, using the back reference to the showtime substring (\1). In the for-loop, the vanquish variable n is a counter for the number of files, and s is the total line count then far.

              #!/bin/bash # Counting the number of lines in a list of files # for loop over arguments  if [ $# -lt 1 ] then   echo "Usage: $0 file ..."   get out i fi  echo "$0 counts the lines of lawmaking"  l=0 n=0 southward=0 for f in $* do 	l=`wc -50 $f | sed 's/^\([0-nine]*\).*$/\one/'` 	echo "$f: $50"         due north=$[ $n + ane ]         due south=$[ $s + $l ] done  echo "$n files in full, with $southward lines in total"            

Version two: Using a Shell Function

In this version we ascertain a function count_lines that counts the number of lines in the file provided as argument. Within the office the value of the argument is retrieved by accessing the variable $ane.

              #!/bin/bash # Counting the number of lines in a list of files # function version  count_lines () {   local f=$i     # this is the return value, i.e. not local   50=`wc -l $f | sed 'south/^\([0-9]*\).*$/\1/'` }  if [ $# -lt 1 ] then   echo "Usage: $0 file ..."   get out 1 fi  repeat "$0 counts the lines of code"  fifty=0 n=0 southward=0 while [ "$*" != ""  ] exercise         count_lines $ane         repeat "$one: $l"         n=$[ $n + 1 ]         s=$[ $s + $fifty ] 	shift done  echo "$n files in total, with $s lines in total"            

Version iii: Using a render code in a function

This version tries to use the return value of the function to return the line count. Nevertheless, this fails on files with more than than 255 lines. The return value is intended to just provide a return code, eastward.thou. 0 for success, 1 for failure, but not for returning proper values.

              #!/bin/bash # Counting the number of lines in a list of files # part version using return lawmaking # WRONG version: the render code is limited to 0-255 #  so this script will run, but impress incorrect values for #  files with more than 255 lines  count_lines () {   local f=$1     local k   1000=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`   return $1000 }  if [ $# -lt i ] then   repeat "Usage: $0 file ..."   exit 1 fi  echo "$0 counts the lines of code"  l=0 n=0 s=0 while [ "$*" != ""  ] practice         count_lines $1 	l=$?         echo "$1: $l"         northward=$[ $n + ane ]         s=$[ $s + $l ] 	shift done  echo "$north files in total, with $s lines in total"            

Version iv: Generating the file listing in a shell part

              #!/bin/fustigate # Counting the number of lines in a list of files # function version  # office storing list of all files in variable files get_files () {   files="`ls *.[ch]`" }  # part counting the number of lines in a file count_lines () {   local f=$i  # 1st argument is filename   50=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'` # number of lines }  # the script should exist chosen without arguments if [ $# -ge 1 ] so   echo "Usage: $0 "   exit ane fi  # split by newline IFS=$'\012'  repeat "$0 counts the lines of code"  # don't forget to initialise! l=0 northward=0 due south=0 # call a role to get a list of files get_files # iterate over this listing for f in $files do         # call a function to count the lines         count_lines $f         echo "$f: $50" 	# increase counter         northward=$[ $n + 1 ] 	# increase sum of all lines         south=$[ $s + $l ] washed  repeat "$northward files in full, with $s lines in total"            

Version 5: Using an array to store all line counts

The instance below uses crush arrays to shop all filenames (file) and its number of lines (line). The elements in an array are referred to using the usual [ ] notation, east.one thousand. file[1] refers to the beginning element in the array file. Note, that bash only supports i-dimensional arrays with integers every bit indizes.

See the section on arrays in the Advanced Bash-Scripting Guide:.

              #!/bin/bash # Counting the number of lines in a listing of files # part version  # function storing list of all files in variable files get_files () {   files="`ls *.[ch]`" }  # function counting the number of lines in a file count_lines () {   f=$i  # 1st argument is filename   fifty=`wc -l $f | sed 's/^\([0-9]*\).*$/\ane/'` # number of lines }  # the script should be called without arguments if [ $# -ge ane ] and so   repeat "Usage: $0 "   exit 1 fi  # split past newline IFS=$'\012'  echo "$0 counts the lines of code"  # don't forget to initialise! l=0 n=0 south=0 # telephone call a function to get a listing of files get_files # iterate over this list for f in $files do         # call a office to count the lines         count_lines $f         echo "$f: $l"loc 	# store filename in an array 	file[$n]=$f 	# shop number of lines in an array 	lines[$n]=$l 	# increase counter         north=$[ $n + 1 ] 	# increase sum of all lines         southward=$[ $s + $50 ] done  repeat "$n files in full, with $s lines in full" i=five echo "The $i-th file was ${file[$i]} with ${lines[$i]} lines"            

Version 6: Count only files nosotros own

              #!/bin/fustigate # Counting the number of lines in a list of files # for loop over arguments # count only those files I am possessor of  if [ $# -lt 1 ] and so   echo "Usage: $0 file ..."   exit ane fi  echo "$0 counts the lines of lawmaking"  fifty=0 northward=0 southward=0 for f in $* do   if [ -O $f ] # checks whether file owner is running the script   then        l=`wc -l $f | sed 'southward/^\([0-9]*\).*$/\ane/'`       echo "$f: $l"       n=$[ $north + ane ]       s=$[ $south + $50 ]   else       continue   fi done  repeat "$n files in total, with $s lines in full"            

Version seven: Line count over several files

The final example supports options that tin be passed from the command-line, e.g. by ./loc7.sh -d 1 loc7.sh. The getopts shell function is used to iterate over all options (given in the following string) and assigning the current choice to variable proper name. Typically it is used in a while loop, to set shell variables that volition be used later. We utilise a pipage of cat and awk to print the header of this file, up to the first empty line, if the help option is chosen. The main part of the script is a for loop over all non-option control-line arguments. In each iteration, $f contains the name of the file to process. If the date options are used to narrow the scope of files to process, we use the date and an if-statement, to compare whether the modification time of the file is within the specified interval. Merely in this case practise we count the number of lines equally before. Subsequently the loop, we impress the total number of lines and the number of files that have been candy.

Example 11. Version seven: Line count over several files

                #!/bin/bash ############################################################################ # # Usage: loc7.sh [options] file ... # # Count the number of lines in a given list of files. # Uses a for loop over all arguments. # # Options: #  -h     ... help message #  -d n ... consider only files modified inside the last n days #  -w n ... consider only files modified inside the last north weeks # # Limitations:  #  . only one option should be given; a second ane overrides # ############################################################################  help=0 verb=0 weeks=0 # defaults days=0 m=ane str="days" getopts "hvd:w:" name while [ "$proper noun" != "?" ] ; do   instance $name in    h) help=1;;       v) verb=1;;       d) days=$OPTARG       m=$OPTARG       str="days";;    w) weeks=$OPTARG       m=$OPTARG       str="weeks";;   esac    getopts "hvd:w:" name washed  if [ $help -eq one ]  so no_of_lines=`cat $0 | awk 'Brainstorm { n = 0; } \                                  /^$/ { print n; \                                         exit; } \                                       { n++; }'`       echo "`head -$no_of_lines $0`"       leave  fi  shift $[ $OPTIND - 1 ]  if [ $# -lt 1 ] and then   echo "Usage: $0 file ..."   exit 1 fi  if [ $verb -eq one ]   and so echo "$0 counts the lines of code"  fi  l=0 northward=0 south=0 for f in $* do   x=`stat -c "%y" $f`   # modification date   d=`date --engagement="$ten" +%y%m%d`   # date of $k days/weeks ago   e=`appointment --date="$thou $str ago" +%y%k%d`   # at present   z=`appointment +%y%m%d`   #echo "Stat: $x; At present: $z; File: $d; $m $str agone: $eastward"   # checks whether file is more recent and so req   if [ $d -ge $e -a $d -le $z ] # ToDo: fix yr wrap-arounds   so        # exist verbose if nosotros found a recent file       if [ $verb -eq i ]          and so echo "$f: modified (mmdd) $d"       fi       # do the line count       l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`       echo "$f: $l"       # increase the counters       n=$[ $due north + 1 ]       s=$[ $south + $50 ]   else       # not strictly necessary, because it's the end of the loop       continue   fi done  repeat "$n files in total, with $s lines in full"              
Note Practise

Extend Version 7 of the line count example to a higher place, to also compute the total number of bytes and the full number of words in the input file.

                        $                        ./loc8.sh text_file.txt  loc8.sh 2 files in total, with 1494438 bytes, 746 words, 27846 lines in total                      
Hint: check the man page for wc.

johnsonsathect87.blogspot.com

Source: http://www.macs.hw.ac.uk/~hwloidl/Courses/LinuxIntro/x864.html

0 Response to "Read Multiple Numbers in Shell Scripting Then Print the Sum of All the Numbers"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel