【问题标题】:How can I get the exact number of lines in while read loop?如何获得 while read 循环中的确切行数?
【发布时间】:2014-06-20 16:26:12
【问题描述】:

我在 shell 脚本中使用了一个 while 读取循环来逐行计算和编号我的 file.txt。现在我想在循环内给出确切的行数,就像我是命令 wc -l 一样。下面是我的脚本。

#!/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};
          # echo $j
          if [[ $h>=11 ]]; then
              if [[ $h<=18 ]] && [[ $s<=00 ]]; then
                  if [[ $m != 01 ]]; then # spaces around "!=" is necessary
                      echo "$count $LINE" $cdat $ctim $clat $clon  
                      let count=$count+1
                  fi
              fi 
          fi
       done  <  cloud.txt 
  exit

输出包含如下行:

0  2014/04/00 14:44:00 26.12 -23.22
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

我的问题是如何找到输出包含 9 行?

【问题讨论】:

  • $count 有什么问题?
  • 您希望在输出中的哪个位置看到“9”? 9行之前?后?而不是?

标签: bash shell


【解决方案1】:

这并不能回答您的具体问题

      if [[ $h>=11 ]]; then
          if [[ $h<=18 ]] && [[ $s<=00 ]]; then

所有这些测试总是返回真

test[[[ 命令根据它们看到的参数数量的不同而有所不同。 所有这些测试都有 1 个单一参数。在这种情况下,如果它是一个非空字符串,你就有一个成功的返回码。

在运算符周围放置空格至关重要。

      if [[ $h >= 11 ]]; then
          if [[ $h <= 18 ]] && [[ $s <= 00 ]]; then

问你的问题:你希望这个测试做什么? [[ $s &lt;= 00 ]]

请注意,这些都是词法比较。你可能想要这个:

      # if hour is between 11 and 18 inclusive
      if (( 10#$h >= 11 && 10#$h <= 18 )); then

【讨论】:

  • [[ $s
  • 那你要:if [[ $h &gt;= 12 &amp;&amp; $h &lt;= 17 ]] || [[ $ctim == "18:00:00" ]]
  • 对了,我想知道12:00:00到18:00:00之间有多少行?
  • 您的条件:如果 [[ $h >= 12 && $h =11 && $h
  • 如果你想在12:00开始,你不能有[[ $h &gt;= 11 ]]。并且,请拜托,如果您从我的回答中得到一件事,那就是 [[ $h&gt;=11 ]][[ $h &gt;= 11 ]]非常不同。
【解决方案2】:

您已经通过 $count 知道了这个值。由于您是从 0 开始计数,因此您想要的数字是 $count+1。

【讨论】:

  • 是的,但我想在我的循环中添加一个命令,它只能打印出数字 9,以仅显示有多少行包含我的输出。
【解决方案3】:

如果我在循环末尾添加命令“wc -l”,我可以得到我想要的,这意味着行数(9 行)。但我想知道是否有办法在循环中完全获取它,也许使用相同的命令“wc -l”。

#!/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>=11 && $h<=17 ]] || [[ $ctim == "18:00:00" ]]; then
               echo "$count $LINE" $cdat $ctim $clat $clon  
               let count=$count+1         
           fi

       done  <  cloud.txt | wc -l 

退出

结果就是:9

但是现在如何在循环内部进行呢?

【讨论】:

    猜你喜欢
    • 2013-01-02
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2022-12-17
    • 2020-08-13
    • 2023-04-05
    相关资源
    最近更新 更多