Issue
I tried solving the problem but I cannot solve the last part where it is given as "Assume the filename is given as command line argument"
Write a shell script which displays the total number of words, characters, lines in a file. Assume the file name is given as command line argument.
echo
c=$( wc -c < test.txt)
echo "Number of characters in test.txt is $c"
echo
w=$( wc -w < test.txt)
echo "Number of words in test.txt is $w"
echo
l=$( ec -l < test.txt)
echo "Number of lines in test.txt is $l"
I had to pass 2 test cases but I'm only passing one test case as I'm unable to solve the problem assuming the filename as command line argument.
Solution
This should work. Write a script the_script.sh as follows:
for F in ${*}
do
echo
c=$( wc -c < ${F})
echo "Number of characters in ${F} is $c"
echo
w=$( wc -w < ${F} )
echo "Number of words in ${F} is $w"
echo
l=$( wc -l < ${F})
echo "Number of lines in ${F} is $l"
done
To explain, ${*}
is ll the command line args passed in, and when used with teh for
loop as above each argument is assin to $F
in each iteration of the loop.
Then within the loop, refer to ${F}
as the file name.
To run:
./the_script.sh text.txt test2.txt ....
As others have noted you should avoid running wc
three times if the files are large, so here is one way to run it just once and process the counts:
WC=$( wc ${F} )
l=$( echo $WC | awk '{print $1}' )
w=$( echo $WC | awk '{print $2}' )
c=$( echo $WC | awk '{print $3}' )
Answered By - TenG