为什么我不能在这个脚本中创建总单词的总和?我得到的结果如下:
120+130
Run Code Online (Sandbox Code Playgroud)
但它不是250(正如我所料)!有什么缘故吗?
#!/bin/bash
while [ -z "$count" ] ;
do
echo -e "request :: please enter file name "
echo -e "\n\tfile one : \c"
read count
itself=counter.sh
countWords=`wc -w $count |cut -d ' ' -f 1`
countLines=`wc -l $count |cut -d ' ' -f 1`
countWords_=`wc -w $itself |cut -d ' ' -f 1`
echo "Number of lines: " $countLines
echo "Number of words: " $countWords
echo "Number of words -script: " $countWords_
echo "Number of words -total " $countWords+$countWords_
done
if [ ! -e $count ] ; then
echo -e "error :: file one $count doesn't exist. can't proceed."
read empty
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
echo"单词数量 - 总数"$ countWords + $ countWords_
你要这个:
echo "Number of words -total $((countWords + countWords_))"
Run Code Online (Sandbox Code Playgroud)
以下是对脚本的一些优化.
while自循环似乎毫无意义count将会被置为确保内使之成为一个1迭代while循环.if对文件的存在检查应该发生你曾经使用该文件之前.itself,您可以使用$0它bash我冒昧地删除了cut使用进程替换的需要.这是修改后的脚本:
#!/bin/bash
echo -e "request :: please enter file name "
echo -e "\n\tfile one : \c"
read count
if [ ! -e "$count" ] ; then
echo "error :: file one $count doesn't exist. can't proceed."
exit 1
fi
itself="$0"
read countWords _ < <(wc -w $count)
read countLines _ < <(wc -l $count)
read countWords_ _ < <(wc -w $itself)
echo "Number of lines: '$countLines'"
echo "Number of words: '$countWords'"
echo "Number of words -script: '$countWords_'"
echo "Number of words -total $((countWords + countWords_))"
Run Code Online (Sandbox Code Playgroud)