用于验证列的shell脚本

时间:2015-02-09 16:34:21

标签: bash shell csv

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

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

所以它必须首先检查coulmn NAMES才能继续检查City?我将如何更改以下脚本以满足此需求?

       # 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

1 个答案:

答案 0 :(得分:0)

我会在内循环中使用awk

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

^prefix1^prefix2是正则表达式。