计算文件中的总记录数并与预告片记录进行比较

时间:2017-03-31 15:30:27

标签: shell

该文件的内容如下

101,abc,2017-03-15,Linux
222,xyz,2016-10-10,Unix
987,def,2017-01-03,Solaris
567,tek,2014-01-09,windows
Trailer|20170331|4

我需要比较4的实际记录行,等于预告片(4)上的总记录。

1 个答案:

答案 0 :(得分:0)

我做了几个假设:

  1. 只会有您想要计算的记录和单个预告片记录。也就是说,没有其他类型的数据记录,没有标题,没有额外的预告片或小计记录。
  2. 在预告片记录中,记录计数将始终是第三个字段,分隔符将始终是管道(“|”)。
  3. 您没有指定您正在使用的特定操作系统或shell,因此您可能需要调整一些命令,因为它们之间存在细微差别。

    无论如何,这就是我提出的:

    recchk()
    {
      #Here's the file we're working with:
      myfile=testfile.txt
    
      #Let's figure out how many records are in it
      recs=`wc -l $myfile | cut -f1 -d" "`
    
      #Now subtract 1 because we don't want to count the trailer
      let recs=`expr $recs - 1`
    
      echo "There are $recs data records in the file."
    
      #Now we'll find the trailer record and get the third field 
      trcnt=`tail -1 $myfile | cut -f3 -d"|"`
    
      echo "Trailer says there are $trcnt records."
    
      #Now we'll check to make sure all is well.
      if [ $recs -ne $trcnt ]; then
         echo "Uh-oh!  They don't match\!"
      else
         echo "Right on, daddy-o\!  We're righteous\!"
      fi
    }
    

    希望这有帮助!