Bash 如何检查一行的语法是否正确?
如果我有以下行语法Bash 如何检查一行的语法是否正确?,bash,shell,Bash,Shell,如果我有以下行语法 FirstName, FamilyName, Address, PhoneNo 我正在读取一个包含信息的数据文件,如何检查我读取的行是否具有正确的语法 更新:: check(){ x=$(echo "$@" | grep -q '^[^,]\+,[^,]\+,[^,]\+,[^,]\+$') return $x } len=#number of lines in the file i=1 while [ $i -le $len ]; do line=$(cat $file
FirstName, FamilyName, Address, PhoneNo
我正在读取一个包含信息的数据文件,如何检查我读取的行是否具有正确的语法
更新::
check(){
x=$(echo "$@" | grep -q '^[^,]\+,[^,]\+,[^,]\+,[^,]\+$')
return $x
}
len=#number of lines in the file
i=1
while [ $i -le $len ]; do
line=$(cat $file)
#------this is where i call the func-----
check $line
if [ $? -eq 1 ];then
echo "ERROR"
else
echo "Good Line"
fi
我的意思是每行发送一个函数(从while循环),如果行正确,它返回0,如果行不正确,它返回1
更新2::
check(){
x=$(echo "$@" | grep -q '^[^,]\+,[^,]\+,[^,]\+,[^,]\+$')
return $x
}
len=#number of lines in the file
i=1
while [ $i -le $len ]; do
line=$(cat $file)
#------this is where i call the func-----
check $line
if [ $? -eq 1 ];then
echo "ERROR"
else
echo "Good Line"
fi
正确的形式是
first name(string), last name(string), address(string), phone no.(string)
因此,如果该行缺少一个或超过4,则应返回1,,
使用Bash,
好的输入是:
Rami, Jarrar, Jenin - Wadi berqen, 111 111
#一些需要处理的案例
, Jarrar, Jenin - Wadi berqen, 111 111
- Extra Spaces::
Rami, Jarrar, Jenin - Wadi berqen, 111 111
Rami, Jarrar, Jenin - Wadi berqen, 111 111, 213 3123
还有另一个更新:)
BASH 2.3.39
*GREP 2.5.3*
更新
现在,如果我使用如下正确格式::
string, value, value, value
值:是一个正整数
此行应替换的内容::
x=$(echo "$@" | grep -q '^[^,]\+,[^,]\+,[^,]\+,[^,]\+$')
?允许空字段:
check () { echo "$@" | grep -q '^[^,]*,[^,]*,[^,]*,[^,]*$'; }
check () { local IFS=,; set -- $@; return $(test -n "$4" -a -z "$5"); }
check () { [[ $@ =~ ^[^,]*,[^,]*,[^,]*,[^,]*$ ]]; }
check () { [[ $@ =~ ^[^,]+,[^,]+,[^,]+,[^,]+$ ]]; }
不允许任何字段为空:
check () { echo "$@" | grep -q '^[^,]\+,[^,]\+,[^,]\+,[^,]\+$'; }
Bourne shell不使用外部实用程序(允许空字段):
Bash 3.2或更高版本(允许空字段):
Bash 3.2或更高版本(不允许空字段):
正确地抛出除示例好行以外的所有行,包括“太多空格”的情况。唯一失败的地方是字段中只有一个字符。如果不定义“正确”行是什么,则无法回答该问题。任何带3个逗号的都是正确的吗?您是否验证电话的数字/长度?设置x值是将命令的输出输出到stdout,而不是返回码。按照Sorpigal在下面的评论中的建议,使用
check(){echo…| grep…}
,或者使用return$?
而不是return$x
。变量$x
将始终为空(因此当返回它时为0),因为-q
选项用于grep
。顺便说一句,“format”在这个上下文中可能比“syntax”更好。在第二个上下文中,如果我省略名字,那么如果行是:last name(string)、address(string)、phone no。(字符串)它返回0,,!!!@Rami Jarrar:在我修复它(将$1
更改为$@
)后您尝试过吗?是的,同样的结果它只返回一个0,,@Rami Jarrar:我每个都得到一个1:检查,最后一个,地址,电话;“echo$?,检查,最后一个,地址,电话;echo$?
,字符串=“,最后一个,地址,电话”;check$string;echo$?;check“$string”;echo$?
。如果我在每个逗号前添加“first”,我会得到一个0。您如何调用函数以及如何检查返回值?Bash的哪个版本以及grep的哪个版本
?对于grep-grep案例,我会简单地说check(){grep-q'^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*$'
line 0 ok
Invalid syntax on line 1
Invalid syntax on line 2
Invalid syntax on line 3
Invalid syntax on line 4
line 5 ok
Invalid syntax on line 6
line 7 ok