if i have the following line syntax
FirstName, FamilyName, Address, PhoneNo
and i am reading a data file that contain information, how can i check that i reads a line with the right syntax ??
UPDATE::
i mean a function i send to it each line (from a while loop), and its return 0 if the line is correct and 1 if the line is not ?
UPDATE2::
the correct form is
first name(string), last name(string), address(string), phone no.(string)
so if the line is missing one or if there more than 4,, it should return a 1,,
Using Bash,
Good Input is ::
Rami, Jarrar, Jenin - Wadi berqen, 111 111
# Some Cases To Deal With
, Jarrar, Jenin - Wadi berqen, 111 111
- Extra Spaces::
Rami, Jarrar, Jenin - Wadi berqen, 111 111
Rami, Jarrar, Jenin - Wadi berqen, 111 111, 213 3123
ALSO ANOTHER UPDATE :)
check(){
x=$(echo "$@" | grep -q '^[^,]\+,[^,]\+,[^,]\+,[^,]\+$')
retur开发者_运维百科n $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
BASH 2.3.39 *GREP 2.5.3*
UPDATE now if i make the correct format like this ::
string, value, value, value
value : is a positive integer
what this line should be replaced ::
x=$(echo "$@" | grep -q '^[^,]\+,[^,]\+,[^,]\+,[^,]\+$')
??
Allows empty fields:
check () { echo "$@" | grep -q '^[^,]*,[^,]*,[^,]*,[^,]*$'; }
Does not allow any field to be empty:
check () { echo "$@" | grep -q '^[^,]\+,[^,]\+,[^,]\+,[^,]\+$'; }
Bourne shell without using external utilities (allows empty fields):
check () { local IFS=,; set -- $@; return $(test -n "$4" -a -z "$5"); }
Bash 3.2 or greater (allows empty fields):
check () { [[ $@ =~ ^[^,]*,[^,]*,[^,]*,[^,]*$ ]]; }
Bash 3.2 or greater (does not allow empty fields):
check () { [[ $@ =~ ^[^,]+,[^,]+,[^,]+,[^,]+$ ]]; }
is_correct () {
grep -q '^[^ ][^,]\+, [^ ][^,]\+, [^ ][^,]\+, [^ ][^,]\+$' <<< "$@"
}
l=0
while read line ; do
is_correct "$line" && echo line $l ok || echo Invalid syntax on line $l
((l+=1))
done <<<"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
A line, containg fields with, many spaces, but otherwise valid
a, b, c, d
aa, bb, cc, dd"
Yields:
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
Correctly throws out the all but the sample good line, including the "too many spaces" case. The only place where it fails is if a field has only one character in it.
精彩评论