Introducing UNIX and Linux |
More on shellsOverview |
Answer to chapter 8 question 3This exercise requires the use of the # Check number of arguments if [ $# -ne 1 ] then echo "Requires one argument" exit 1 # If a single argument, check it's readable elif [ ! -r $1 ] then echo "File is unreadable" exit 1 fi LINES=0 # To count number of lines COL=0 # To count number of characters while read LINE # read returns false at end of input do # Characters on line (including Newline) COLONLINE=$( echo "$LINE" | wc -c ) # Add to COL and subtract 1 for the Newline COL=$(( $COL + $COLONLINE - 1 ) # Increment line count LINES=$(( $LINES + 1 ) done <$1 # Input from the file # Since 2 decimal places needed, must use bc to # calculate the average, not arithmetic expansion AVERAGE=$( echo "scale=2; $COL / $LINES" | bc ) # Finally, display the average printf "Average is %s\n" $AVERAGE |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck