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

    def something...
        random text


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
    Commented Dec 7, 2017 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
    Commented Dec 7, 2017 at 22:53
  • 3
    bash is not a text processing tool, just so you know. Commented Dec 7, 2017 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
    Commented Dec 7, 2017 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
    Commented Dec 7, 2017 at 23:08

1 Answer 1


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"}'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .