验证标题中的记录计数

验证标题中的记录计数

我正在尝试编写一个脚本,该脚本应验证总详细记录等于Record_count标头记录,如果不抛出错误

样本数据

0001  HD  SAP _AP Distribution  20150615  131723  000003  00000003   

detail record 1
detail record 2
detail record 3

标题中00000003是记录数

答案1

使用awk

awk '! /^detail/ && /.+/ {max=$9} /^detail record/ {count++} END {if (max == count) { print "ok, "max" = "count} else { print "not ok, "max" != "count }}' foo

或者作为 bash 脚本

#!/bin/bash
retValue=$(awk '! /^detail/ && /.+/ {max=$9} /^detail record/ {count++} END {if (max != count) { print "1" }}' "$1")

if [[ "$retValue" -eq 1 ]]; then
    exit 1
fi

exit 0

启动脚本:

<script_name> <data_file>

例子

% cat foo                                                                    
0001  HD  SAP _AP Distribution  20150615  131723  000003  00000003   

detail record 1
detail record 2
detail record 3

% awk '! /^detail/ && /.+/ {max=$9} /^detail record/ {count++} END {if (max == count) { print "ok, "max" = "count} else { print "not ok, "max" != "count }}' foo
ok, 00000003 = 3

% cat bar
0001  HD  SAP _AP Distribution  20150615  131723  000003  00000004   

detail record 1
detail record 2
detail record 3

% awk '! /^detail/ && /.+/ {max=$9} /^detail record/ {count++} END {if (max == count) { print "ok, "max" = "count} else { print "not ok, "max" != "count }}' bar
not ok, 00000004 != 3

答案2

缩短的awk脚本期望输入格式与您的示例完全相同(它[仅]将第一行的第9个字段中包含的数字与总行数减去2进行比较):

< in awk 'NR==1 {c=$9} END {if (c==FNR-2) print "ok"; else print "ko"}'

相关内容