0

I wish to write a bash script that will read a file containing 100s of lines and look for the pattern def <space>, if this pattern is found in the line, it will check the next line to see if the pattern ''' is present in this next line. If yes, then it checks if the next ''' is encountered 5 lines away. If all of these are yes, echo TRUE, else echo FALSE.

For example, file 1:

line 1
line2
...

    def something...
        '''
        random text
        rand..text
        rand..
        ra..


        '''

echoes TRUE

File 2:

line 1
line 2
...

    def something..
        int a
        ...

echoes FALSE

There can be multiple such def <space> patterns within the file and if any of them fails the test, the overall result is FALSE.

How do I do this using awk, grep, or sed?

  • 2
    You could do this with a complex and fragile shell script, but since you're working with Python, it would likely be easier to do this with pure python. You could, for instance, iterate over the functions defined in the current scope and inspect their docstrings. – jayhendren Dec 7 '17 at 22:52
  • I understand what you mean. But we are testing student codes on a third-party environment which lets us create test cases using bash only. – learnerX Dec 7 '17 at 22:53
  • 3
    bash is not a text processing tool, just so you know. – don_crissti Dec 7 '17 at 22:54
  • 3
    You're testing student code and you want to check if their code has 5-line docstrings? Without knowing much more about your situation, this sounds like an ineffective test of students' Python knowledge to me. – jayhendren Dec 7 '17 at 22:55
  • Since you're using bash, could you write a Python script that contains the test cases and then call python -c 'inline script here' or python /path/to/script? – jayhendren Dec 7 '17 at 23:08
0

Try this, will explain if this is what you're looking for.

 grep -A5 "def " file.txt | grep -n "'''" | awk -F ':' '{print $1}' | tr '\n' ' ' | awk  '{if ($1 == "2" && $2 == "" ) print "TRUE";else print "FALSE"}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.