unix 使用嵌套的for循环编写bash脚本来验证任意两个字段记录中的字符和数据类型是否匹配[重复]

gmxoilav  于 2023-01-13  发布在  Unix
关注(0)|答案(1)|浏览(209)
    • 此问题已存在**:

Write a unix bash script to check , file has malformed record [closed]
3天前关闭。
此帖子已于3天前编辑并提交审核,未能重新打开帖子:
原始关闭原因未解决
样本数据:

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

这里表头的字段数是7,我们需要检查任意两个字段记录中的字符是否匹配,还需要检查字段的数据类型是否与其记录匹配。
要求:
需要使用嵌套的for循环来执行任意两个或三个字段记录的验证。

agxfikkp

agxfikkp1#

注意:不要忘记if语句使用==进行比较,而不是=,否则我认为如果您更正此错误,您的代码可能会工作。

我像这样复制了设置。我添加了几行,有更多/更少的字段用于演示。sample_data.txt的内容:

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 |1001 |Samsung |Handset |R2R003 |Online |extra |Credit Card |100|
Data |1001 |Samsung |Online |Credit Card |100|
Data | 1004|LG |TV | R2R042| Online | Debit card|150.24|
Trailer | 2

下面是脚本test.sh:

#!/bin/bash
header_field_count=$(cat sample_data.txt | awk -F '|' '{print NF}' |head -1)
echo 'header_field_count:' $header_field_count
number_of_lines=$(wc -l < sample_data.txt)
echo 'number of lines to process in file:' $number_of_lines
let current_line=2 #skip 1st line because that is header
data_field_count_array=($(cat sample_data.txt | awk -F '|' '{print NF -1}')) # note NF -1 because these lines have an extra separator at the end
while [ $current_line -lt $number_of_lines ]; do
  echo 'line:' $current_line 'has' ${data_field_count_array[$current_line-1]} 'fields' #bash arrays are zero indexed therefore the -1 (line 1 is index 0)
  if [[ ${data_field_count_array[$current_line-1]} == $header_field_count ]]; then
    echo 'EQUAL to the Header'
  else
    echo 'NOT EQUAL to the Header'
  fi
  let current_line+=1
done

运行时,输出如下:

header_field_count: 8
number of lines to process in file: 6
line: 2 has 8 fields
EQUAL to the Header
line: 3 has 9 fields
NOT EQUAL to the Header
line: 4 has 6 fields
NOT EQUAL to the Header
line: 5 has 8 fields
EQUAL to the Header

它将与任意数量的数据线一起工作

相关问题