Linux shell脚本中的求和
为什么我不能在这个脚本中创建一个单词总数?我得到的结果是:Linux shell脚本中的求和,linux,shell,sum,Linux,Shell,Sum,为什么我不能在这个脚本中创建一个单词总数?我得到的结果是: 120+130 但它不是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
120+130
但它不是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
一种方法是:
echo `expr $countWords + $countWords_`
回显“字数-总数”
$countWords+$countWords_
你想要这个:
echo "Number of words -total $((countWords + countWords_))"
编辑
下面是对脚本的一些优化
while
循环似乎毫无意义
因为count
将被设置为
当然,这是一个好主意
1-边循环边迭代if
检查是否存在
文件应该在您之前发生
使用该文件本身
,您可以使用$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_))"
#/bin/bash
echo-e“请求::请输入文件名”
echo-e“\n\t文件一:\c”
读取计数
如果[!-e“$count”];然后
echo“错误::文件1$count不存在。无法继续。”
出口1
fi
本身=“$0”
read countWords<expr
已被弃用,请使用$(())
instead@SiegeX,$(())
是bash语法,不要破坏posix bourne shell。$(())
是shell;它也是Korn shell(和Bash);“这不是伯恩·谢尔。”乔纳森,谢谢你帮我做了这件肮脏的工作。即使$(())
不是POSIX语法,\/bin/bash
在他的脚本顶部将使这一点变得非常重要。不要使用
,使用“代码示例(ctrl-K)”按钮。countWords=$(wc-w<“$count”)
将获得不带文件名的计数。或者您可以使用一个调用wc
,而不是两个:读取countLines countWords