【问题标题】:A shell script to validate a column用于验证列的 shell 脚本
【发布时间】:2023-04-06 02:56:01
【问题描述】:

我有这个脚本将读取目录中的 csv 文件。但是我希望脚本在移动到第二列之前验证整个 .csv 文件,即

Name, City
Joe, Orlando
Sam, Copper Town
Mike, Atlanta

所以它必须先检查列名,然后再继续检查城市?我将如何对以下脚本进行更改以适应这种情况?

       # Read all files.  no file have spaces in their names
  for file in /source/*.csv ; do
         # init two variables before processing a new file
  FILESTATUS=GOOD
  FIRSTROW=true
       # process file 1 line a time, splitting the line by the 
       # Internal Field Sep ,
  cat "${file}" | while IFS=, read field1 field2; do
       # Skip first line, the header row
  if [ "${FIRSTROW}" = "true" ]; then
     FIRSTROW=FALSE
        # skip processing of this line, continue with next record
     continue;
  fi

        #different validations
  if [[ "${field1}" = somestringprefix*  ]]; then
     ${FILESTATUS}=BAD
     # Stop inner loop
     break
  fi
  somecheckonField2
  done
    if [ ${FILESTATUS} = "GOOD" ] ; then
      mv ${file} /source/good
    else
      mv ${file} /source/bad
    fi
 done

【问题讨论】:

    标签: bash shell csv


    【解决方案1】:

    我会在内循环中使用awk

    if awk -F, '$1 !~/^prefix1/ || $2 !~ /^prefix2/ {exit(1)}' "$file" ; then
        mv "$file" good
    else
        mv "$file" bad
    fi
    

    ^prefix1^prefix2 是正则表达式模式。

    【讨论】:

    • 谢谢,但是上面的脚本,它是否迭代垂直检查列中的每个字段而不是水平检查,这是传统的方法
    • 逐行验证。但如果一行无效,它会停止对该文件的进一步处理并返回1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多