In this stage, we derive a histogram of line-lengths. You must write a shell-scr
ID: 3819277 • Letter: I
Question
In this stage, we derive a histogram of line-lengths. You must write a shell-script named histo that can be called in either of two ways: histo filename, which reads the file named filename; or histo, which reads from standard-input. Output the histogram like this: 1 4 2 10 3 9 4 12 6 17 20 4 Where the first number is the length of the line, and the second number is the number of lines that were found with that length. If there are no lines of length, say 5, omit the line 5 0 from the output. Notice that there are no spaces before the first number. Test your program thoroughly!Explanation / Answer
Explanation: read from the file or standard input line be line and keep track of the max line length. If no filename specified in the argument then it reads from command line and store the lines in file1.txt(Until you enter "quit"). Then process file1.txt. Otherwise read from the filename specified.
Create an array of max line length. Calculate the length of each line and increment the corresponding index in the array.
For each element in the array print the index(line length) with value(no of lines with that length ) , if val not equal to 0(means no of lines with that length is not zero)
code:
if test $# -eq 0
then
FILENAME="file1.txt"
while read CMD && [ "$CMD" != "quit" ]
do
echo $CMD >> $FILENAME
done
else
FILENAME=$1
fi
count=0
max=0
while read LINE
do
var=arr[${#LINE}]
if test $max -lt ${#LINE}
then
max=${#LINE}
fi
done < $FILENAME
declare -a arr
for ((i=0;i<$max;i++))
do
arr[$i]=0
done
while read LINE
do
var=arr[${#LINE}]
let arr[${#LINE}]++
done < $FILENAME
lengthcount=0
for each in "${arr[@]}"
do
if test $each -ne 0
then
echo "$lengthcount $each"
fi
let lengthcount++
done
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.