2017-03-31 55 views
0

文件的内容比较有如下总计数记录,并用拖车记录

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)。

+0

您是否尝试过自己解决问题? – Inian

+0

您想如何获得输出? – Inian

回答

0

我已经做了几个假设:

  1. 将有永远只能是你要算记录和一个尾部记录。也就是说,没有其他类型的数据记录,没有标题,没有额外的预告片或小计记录。
  2. 在挂车记录上,记录计数将始终为第三个字段,分隔符将始终为管道(“|”)。

你没有指定你正在使用什么特定的操作系统或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 
} 

希望这有助于!

+0

谢谢罗杰,工作完全正常,只需要上面的一个更多的信息,我如何通过文件名作为参数在函数recchk(),以便这可以跨多个脚本使用。 –

+0

如果您将recchk()函数放入单独的文件(如recchk.sh)中,则可以使用'source /recchk.sh'将其导入另一个脚本中。然后,您可以像使用其他脚本一样使用rechchk()函数。 –

+0

假设我有5个文本文件,并且对于每个文件,我必须检查记录的总数并与拖车记录进行比较,看它是否匹配。显然5个文件会有不同的名称,我想通过在函数recchk()中传递文件名来重用它们,我怎样才能调用文件名 –