You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用嵌套for循环编写Bash脚本验证字段字符与数据类型匹配性

Bash脚本优化:多字段验证与数据类型校验

需要使用嵌套for循环编写Bash脚本,实现以下功能:

  • 验证任意两个或三个字段记录的字符是否匹配
  • 校验字段数据类型与记录是否相符

样本数据包含Header、Data、Trailer行,其中Header共7个字段。现有脚本仅支持单字段验证,需优化以支持多字段验证。

样本数据

Header | <Transaction_ID> | <Item_ Name> |<Item_Type> | <Customer_ID> | <Type_of_Transaction> | <Payment_Method>|Amount

Data |1001 |Samsung |Handset |R2R003 |Online |Credit Card |100|

Data | 1004|LG |TV | R2R042| Online | Debit card|150.24|

Trailer | 2

现有代码

#!/bin/bash 

now=`date +"%d_%m_%y" ` 

file=transaction${now}.dat.gz 

#header_fieldc is a parameter which has each header fields in new line 

header_fieldc=`zcat $file | head -1|tr "|" "\n" ` 

a=( $header_fieldc) 

for (( i=0; i<=${#a[@]}; i++ ));do 

  echo "${a[i]}" 

  if [ $i == 0 ];then 

    i=`expr $i + 1 ` 
    rec_fieldc=`zcat $file |sed'1d;$d' 
    |cut -d| -f $i `

  fi 
  #rec_fieldc parameter contains records of ith header field .

  b=( $rec_fieldc )

   for (( j=0; j<=${#b[@]}; j++ ));do 

          echo "${b[j]}" 

          var=`echo "${b[j]}" ` 

          if [[ "${var}" =~ ^[0-9]+$ ]];then 
               echo " ${b[j]} valid" 

           else 
                 echo "invalid character precent in ${a[j]} field" >exception.txt 
                 exit 0 
           fi 
   done

done

现有脚本仅能验证单字段(如Transaction_ID)的有效性,无法完成多字段的字符匹配及数据类型校验。

内容的提问来源于stack exchange,提问作者navy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 08:15:52