首页 > 解决方案 > 检查数据应为两列格式,带逗号 | Unix |

问题描述

我在文件中有数据

File : Student.txt 
AB,A1
BC,A2
CD,A3
  ,A4   --> not in proper format position value is missing  
MM,A5
SD      --> not in proper format position value is missing

How to write code so that the Position 0 : AB , Position 0 : A1  should be with comma (,)

如果其中一个不存在,则两个位置值都应该存在,那么它应该显示消息,例如文件格式不正确

标签: linuxshell

解决方案


你可以试试这个:

#!/bin/bash
msg="not in proper format position value is missing"
while read -r line; do
    col1="${line%,*}"
    col2="${line#*,}"
    [[ -z $col1 || -z $col2 || $line != *","* ]] && echo "'$line' $msg"
done < Student.txt

解释:

-z $col1        check if first column has no value
-z $col2        check if second column has no value
$line != *","*  check if line contains no comma

推荐阅读