How to match the syntax in file if matches display success or fail

我与影子孤独终老i 提交于 2021-01-29 15:14:30

问题


I have a scenario where i have following below data in Student file

My Student.txt data input, need to follow a pattern, on each line need to contains three infos separated by / as follows:

NAME/SURNAME/COUNTRY

So, below I have an example of file that is fine:

    RAM/ABC/INDIA
    RAJ/XYZ/DELHI
    VIRAJ/FDS/GUJRAT

WHAT IS EXPECTED:

Each and every record in file should match with that syntax: NAME/SURNAME/COUNTRY.

If anyone fails then, the overall status should be displayed as failed, with the message syntax does not match, otherwise, mark as success.


WHAT'S HAPPENING:

If I pass data to above code like below:

    RAM/ABC/INDIA
    RAJ/XYZ/DELHI
    VIRAJ/FDS/

When I execute the my code, I don't get any error saying failed: syntax does not match it simply check upto below two records

    RAM/ABC/INDIA
    RAJ/XYZ/DELHI

The last record in file, that is VIRAJ/FDS/ does not check and not thrown error failed: syntax does not match

My code:

    for i in `cat /demo/Student.txt`
      do 
      check=`echo $i | cut -d '/'-f3`
      if [[ -z $check ]];
      then 
        echo failed syntax does not match NAME/SURNAME/COUNTRY
        exit 1 
      fi 
    done 

回答1:


You can solve this using regular expressions, as you can see here:

grep "[A-Z]/[A-Z]*/[A-Z]" test.txt

This shows the following lines:

RAM/ABC/INDIA
RAJ/XYZ/DELHI

Which is caused by following entries which match:

M/ABC/I
J/XYZ/D

If you use grep -v you find the lines which don't match. Launching a wc -l, you find if there are any of such lines and in case yes, you can show your error message.

Some regular expression syntaxes use + as a way to say "one or more entries" (instead of * which means "zero or more entries") but it depends on your system's OS if this works or not.

Can you tell me if this is working out for you?



来源:https://stackoverflow.com/questions/62022172/how-to-match-the-syntax-in-file-if-matches-display-success-or-fail

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!