我是Bourne shell的新手,并且对多行/包含换行符读取stdin感到好奇。
IN:例如,如果有人输入
1
3 #only ignore whitespace
5.3 #ignore floating point number all together
我可以让它读取它们并在不同的行上回显它们。我的目标是忽略浮点数(仅整数!)并忽略空格。
OUT:我理想的输出将计算平均值(例如上面的输入)
1
2
到目前为止,我可以读取标准输入并回显它,如果它在一行上并且限制为硬编码值(应该是用户使用Ctrl-D停止时)。
#! /bin/sh
read a b c
echo "$a";
echo "$b";
echo "$c";
答案 0 :(得分:1)
已经有一段时间了,但是下面的内容应该仅为整数输入获得sum
和average
:
#!/bin/sh
sum=0;
cnt=0
while read line
do
case "$line" in
*[.]* )
continue
;;
[0-9]* )
sum=`expr "$sum" + "$line"`
cnt=`expr "$cnt" + 1`
;;
esac
done
printf "\nThe sum is '%s', cnt is '%s' the average is '%s'\n\n", "$sum" "$cnt" `expr $sum / $cnt`
<强>输出强>
$ printf "1\n 3\n5.3\n" | sh bourne_sum.sh
The sum is '4', cnt is '2' the average is '2'
在文件中输入
$ cat dat/bsum.txt
1
3
5.3
简单的重定向将:
$ sh bourne_sum.sh <dat/bsum.txt
The sum is '4', cnt is '2' the average is '2'
修改为在1行输出
#!/bin/sh
sum=0;
cnt=0
while read line
do
case "$line" in
*[.]* )
printf " 0"
continue
;;
[0-9]* )
sum=`expr "$sum" + "$line"`
cnt=`expr "$cnt" + 1`
printf " %s" `expr $sum / $cnt`
;;
esac
done
printf "\n"
# printf "\nThe sum is '%s', cnt is '%s' the average is '%s'\n\n" "$sum" "$cnt" `expr $sum / $cnt`
<强>输出强>
$ printf "1\n3\n5\n4.4\n" | sh bourne_sum.sh
1 2 3 0
#!/bin/sh
sum=0;
cnt=0
while read line
do
if [ $line -eq $line 2>/dev/null ]
then
sum=`expr "$sum" + "$line"`
cnt=`expr "$cnt" + 1`
printf " %s" `expr $sum / $cnt`
fi
done
printf "\n"
<强>输出强>
$ printf "1\n3\n5\n4.4\n'2 3'\n" | sh bourne_sum.sh
1 2 3