linuxbasharithmetic-expressionswc

How to divide the number of words from the number of characters of a file in bash script using arithmetic expansion and wc


Here is my work:

wc -w $3/lab1.txt

words=$(wc -w $3/lab1.txt)

wc -m $3/lab1.txt

characters=$(wc -m $3/lab1.txt)

echo $((characters / words))

The two variables that I have setup work perfectly and they give the correct output but when I try to divide characters from words using arithmetic expansion. I get an error and I wasn't wondering if I could do it this way or not.

Here's the error: enter image description here


Solution

  • You're assigning the whole output of wc -w and wc -m to variables, where they're followed by the file name. So your variable is actually:

    words="3 /Users/example/lab1.txt"
    characters="16 /Users/example/lab1.txt"
    

    Now when Bash evaluates $(( characters / words )), it's actually doing:

    16 /Users/example/lab1.txt / 3 /Users/example/lab1.txt
    

    In arithmetic expansion, unset variables are treated as zero, so Users=0 and Bash attempts to divide, and gives you the error output.

    You should extract the number part of the output from wc -w. One example is with cut:

    words=$(wc -w $3/lab1.txt | cut -d' ' -f1)
    characters=$(wc -m $3/lab1.txt | cut -d' ' -f1)
    
    echo $((characters / words))  # Voila!
    

    Or use AWK if you're unconfident about leading spaces:

    words=$(wc -w $3/lab1.txt | awk '{print $1}')