Hello Everyone,
I need help on a part of the script below.The purpose is to accept some filenames as command line arguments and count the number of characters,words,lines in each file, and the total of each of these 3 attributes.

My output should look like this...

file 1 stats:
Number of characters: 100
Number of words : 50
Number of lines : 12

file 2 stats:
Number of characters: 200
Number of words : 65
Number of lines : 22


However my output presently looks like this:

$ ./test3 sush.pl sample
expr: syntax error
expr: syntax error
expr: syntax error
file 1 stats :
Number of characters : 75 sush.pl
Number of words : 12 sush.pl
Number of lines : 4 sush.pl

expr: syntax error
expr: syntax error
expr: syntax error
file 2 stats :
Number of characters : 102 sample
Number of words : 23 sample
Number of lines : 12 sample


I need help with taking out the expr: syntax error and the filename..like sush.pl,sample above that comes after each output

My code is as shown below

#!/bin/bash

index=0
sumChar=0
sumWords=0
sumLines=0


for file in $*; do
        if [ -f "$file" ]; then
        {
                index=`expr $index + 1`
                char=`wc -c $file`
                words=`wc -w $file`
                lines=`wc -l $file`

                sumChar=`expr $sumChar + $char`
                sumWords=`expr $sumWords + $words`
                sumLines=`expr $sumLines + $lines`

                echo "file $index stats :"

                echo "Number of characters : $char"
                echo "Number of words : $words"
  	        echo "Number of lines : $lines"
  	        echo " "
         }
         else
        {
                echo "$file does not exist"
        }
        fi

done

Recommended Answers

All 4 Replies

The wc program is outputting the filename after the count which interferes with the arithmetic.

char=`wc -c $file | cut -d' ' -f1`
                words=`wc -w $file | cut -d' ' -f1`
                lines=`wc -l $file | cut -d' ' -f1`

Just store the count in the variable by cutting out everything but the first field.

Thanks Risby but do you know why I keep getting :

expr: syntax error
expr: syntax error
expr: syntax error


for each filename (argument)

Have you tried using his suggestion yet? If you had, you would see that the expression syntax error should now be gone. The problem was that the variables char, words, and lines contained something like "86 filename" rather than just "86". With the above change they will contain just "86". So, the expr syntax error is corrected.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.