怎么做多个" echo $ count"在读取循环结束时?

时间:2014-06-20 14:42:35

标签: bash

我在shell脚本中使用了一个while循环来计算file.txt的12:00:00到18:00:00之间的行数,并且脚本运行良好。现在我想扩展此过程以计算以下时间步之间的行数:

00:00:00 and 05:59:59;
06:00:00 and 11:59:59;
12:00:00 and 17:59:59;
18:00:00 and 23:59:59;

查看第一个脚本,然后是结果

  #!/bin/bash

  let count=0

  while read cdat ctim clat clon
       do
          h=${ctim:0:2};    # substring hours from ctim
          m=${ctim:3:2};
          s=${ctim:6:2};
           if [[ $h -ge 12 && $h -le 17 ]] || [[ $ctim == "18:00:00" ]]; then
             let count=$count+1
             echo $count $cdat $ctim $clat $clon          
           fi

       done  <  cloud.txt 
       echo $count
  exit

结果:

1 2014/11/21 16:05:00 19.56 -05.30
2 2014/01/31 13:55:00 02.00 31.10
3 2014/04/00 14:20:00 17.42 12.14
4 2014/07/25 15:30:00 35.25 05.90
5 2014/05/15 12:07:00 23.95 07.11
6 2014/07/29 17:34:00 44.00 17.43
7 2014/03/20 18:00:00 -11.12 -22.05
8 2014/09/21 12:00:00 06.44 41.55
8

我想做同样的事情,根据相应的时间步骤得到不同的结果,但是在同一个脚本中。我想逐一打印出与上面不同的结果。

2 个答案:

答案 0 :(得分:0)

我会编辑你的初始脚本,把开始和结束时间作为一个参数,然后编写第二个脚本,给你第一个你想要的时间值(只是一个开始和结束时间的列表,也许是一个输出文件,如果你想要计数是分开的)。您需要编辑第一个脚本以忽略开始时间之前的所有内容,然后将18:00:00抽出并用endtime变量替换它。

这样,您可以轻松地在任何时间段内运行报告,并且您已经设置了逻辑来计算必要的数据。

答案 1 :(得分:0)

count=()
total=0
while read cdat ctim rest; do
    if   [[ $ctim == "00:00:00" ]] || [[ "00:00:00" < $ctim && $ctim < "06:00:00" ]]; then
        index=0
    elif [[ $ctim == "06:00:00" ]] || [[ "06:00:00" < $ctim && $ctim < "12:00:00" ]]; then
        index=6
    elif [[ $ctim == "12:00:00" ]] || [[ "12:00:00" < $ctim && $ctim < "18:00:00" ]]; then
        index=12
    else
        index=18
    fi
    (( count[index]++ ))
    (( total ++ ))
    echo ${count[index]} $cdat $ctim $rest
done < file

for index in 0 6 12 18; do
    echo "count between $index and $((index+6)): ${count[index]}"
done
echo total count: $total
相关问题