T2 CPS393 Practice
T2 CPS393 Practice
T2 CPS393 Practice
Write a program that expects one command line argument, the name of an input
file. If the input argument is not a file, print "X is not a file" to stderr, where X is the
argument’s name, and exit with a code of 1.
Each line in the input file contains some combination of words cat, dog, tac, god
(tac and god being cat and dog backwards).
For each line in the file, count the number of cats (and tacs), the number of dogs
(and gods). If there are more cats than dogs print MEOW to stdout. If there are
more dogs than cats, print WOOF. If they are equal, print SAME.
“If the input argument is not a file, print "X is not a file" to stderr, where
X is the argument’s name, and exit with a code of 1.”
done <$1
done <$1
catstr: dogstr:
c d
c c c c c d d d
c d d d
d
c d
(One line per iteration, remember) c c d d
c c c c d d d
done <$1 c
done <$1
#!/bin/bash
if [ ! -f "$1" ] ; then
echo "$1 is not a file" >/dev/stderr So far it’s the same…
exit 1
fi
done
Write a program that reads from stdin and writes to stdout. Each line of
stdin should contain a numeric value, either integer or floating point.
If the number is an integer, simply print that integer back to stdout. If the
number is a float, extract the whole number portion to the left of the
decimal, and the fractional portion to the right of the decimal. Represent
the float as the sum of these two components.
#!/bin/bash
while read x; do While loop to iterate through lines of stdin
else
• If grep finds a dot, string is not
empty, and we have a float.
fi • If not, string is empty, test is false,
done we have an integer.
#!/bin/bash
while read x; do
if [ "`echo $x | grep '\.'`" ]; then
else
If line contains an integer, all we
echo $x
do is print it. Done and done.
fi
done
#!/bin/bash
while read x; do
if [ "`echo $x | grep '\.'`" ]; then
flt=`echo $x | sed -e "s/\./ + 0\./"`
#!/bin/bash
while read x; do
if [ "`echo $x | grep '\.'`" ]; then
flt=`echo $x | sed -e "s/\./ + 0\./"`
echo "${flt} = $x"
else
echo $x • 3 + 0.1415 should be:
fi • 3 + 0.1415 = 3.1415
done • Simply use echo to add = 3.1415