Bourne shell: 读取多行标准输入
Bourne shell: reading multiple lines of stdin
我是 Bourne shell 的新手,对阅读多个标准输入很好奇 lines/that 包括换行符。
IN:例如,如果有人输入
1
3 #only ignore whitespace
5.3 #ignore floating point number all together
我可以让它读取它们并在不同的行中回显它们。我的目标也是忽略浮点数(仅限整数!)并忽略空格。
OUT:我的理想输出会计算平均值(上面输入的示例)
1
2
到目前为止,我可以读取 stdin 并将其回显,如果它在一行上并且限于硬编码值(应该是每当用户使用 Ctrl-D 停止时)。
#! /bin/sh
read a b c
echo "$a";
echo "$b";
echo "$c";
已经有一段时间了,但下面应该只为整数输入获得 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
我是 Bourne shell 的新手,对阅读多个标准输入很好奇 lines/that 包括换行符。
IN:例如,如果有人输入
1
3 #only ignore whitespace
5.3 #ignore floating point number all together
我可以让它读取它们并在不同的行中回显它们。我的目标也是忽略浮点数(仅限整数!)并忽略空格。
OUT:我的理想输出会计算平均值(上面输入的示例)
1
2
到目前为止,我可以读取 stdin 并将其回显,如果它在一行上并且限于硬编码值(应该是每当用户使用 Ctrl-D 停止时)。
#! /bin/sh
read a b c
echo "$a";
echo "$b";
echo "$c";
已经有一段时间了,但下面应该只为整数输入获得 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