我已经写了一个小的shell scipt,但是我不能让if语句工作。
我正在运行一个while循环遍历一个文件(14380行,134列),我想在符合条件number in column 4 > 6 and number in column 4 < 7
的某些行上做一些工作。第4列中的数字是实数,我知道if语句只处理整数。这是我的问题吗?我认为if语句会将我的数字get_lon
读作整数,例如。它会把它读成get_lon=14
。这对be来说是没问题的。很长一段时间后,它不会给出错误消息,但它不会像我想要的那样过滤数据。现在,文件的所有行都通过了测试。
#!/bin/bash/sh
ulimit -s unlimited
datafile=$1
wfno=0
cat $datafile | while read line
do
wfno=`expr $wfno + 1`
echo $wfno
get_lon=`awk '(NR=='$wfno'){print $4}' $datafile`
echo $get_lon
if test ["$get_lon" > "6" -a "$get_lon" < "7"]
then
awk '(NR=='$wfno'){for(i=7;i<=NF;i++){print i-7, $i;}}' $datafile > xy
echo 'awk done '
some more stuff...
else
echo "Line not valid"
fi
done
有人能帮上忙吗?
发布于 2012-10-19 08:17:56
使用-gt
(大于)和-lt
(小于)比较整数。
if ["$get_lon" -gt "6" -a "$get_lon" -lt "7"]
发布于 2012-10-19 09:01:30
您需要在[
后面添加一个空格
同样,下面的代码也适用于我的浮点数:
if [ "$count" -gt 1 -a "$count" -lt 2 ]|bc
测试如下:
> cat temp.sh
#!/bin/sh
count=1.5
if [ "$count" -gt 1 -a "$count" -lt 2 ]|bc
then
echo "yes"
fi
> temp.sh
yes
>
发布于 2014-08-06 12:55:54
测试浮点数时,请改用expr
或bc
:
if expr "$get_lon" '>' 6 && expr "$get_lon" '<' 7; then
...
fi
或
if [ "$(echo "$get_lon > 6" | bc)" = 1 -a "$(echo "$get_lon < 7" | bc)" = 1 ]; then
...
fi
更推荐使用expr
,因为它不需要命令替换。
https://stackoverflow.com/questions/12970054
复制相似问题