[英]How to divide the number of words from the number of characters of a file in bash script using arithmetic expansion and wc
這是我的工作:
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))
我設置的兩個變量工作完美,它們給出了正確的 output 但是當我嘗試使用算術擴展將字符與單詞分開時。 我收到一個錯誤,我不知道我是否可以這樣做。
這是錯誤:在此處輸入圖像描述
您將wc -w
和wc -m
的整個 output 分配給變量,它們后跟文件名。 所以你的變量實際上是:
words="3 /Users/example/lab1.txt"
characters="16 /Users/example/lab1.txt"
現在,當 Bash 評估$(( characters / words ))
時,它實際上是在做:
16 /Users/example/lab1.txt / 3 /Users/example/lab1.txt
在算術擴展中,未設置的變量被視為零,因此Users=0
和 Bash 嘗試除法,並給出錯誤 output。
您應該從wc -w
中提取 output 的數字部分。 一個例子是cut
:
words=$(wc -w $3/lab1.txt | cut -d' ' -f1)
characters=$(wc -m $3/lab1.txt | cut -d' ' -f1)
echo $((characters / words)) # Voila!
或者如果您對前導空格不自信,請使用 AWK:
words=$(wc -w $3/lab1.txt | awk '{print $1}')
您以錯誤的方式使用wc
命令。 如果您想獲取 output 中的數字 - 並且只有數字 - wc
必須從標准輸入讀取。 因此,如果你做一個
words=$(wc -w <$3/lab1.txt)
characters=$(wc -m <$3/lab1.txt)
echo $((characters / words))
您不再收到錯誤消息。
這應該可以回答您的問題,但一方面要注意:由於您使用的是 bash,因此您會將除法截斷為 integer,並且您不必要地解析輸入文件兩次。 如果這對您的應用程序來說是一個問題,那么您可能會完全重新考慮您的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.