简体   繁体   中英

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

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}')

You are using the wc command in the wrong way. If you want to get the number - and only the number - in your output, wc must read from stdin. Hence, if you do a

words=$(wc -w <$3/lab1.txt)
characters=$(wc -m <$3/lab1.txt)
echo $((characters / words))

you don't get the error anymore.

This should answer your question, but one side remark: Since you are using bash, you get the division truncated to an integer, and you unnecessarily parse the input file twice. If this is an issue for your application, you perhaps rethink your approach completely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM