0

I am enforcing coding habits for some students and so I am reading their source files using a bash script and I need to find if they have the pattern 'class ' in the beginning of the line (indentation may or may not be present before this pattern in the line). If the pattern is found then the next character needs to be checked for uppercase. For e.g.:

    class Camel
    class camel

Read the first line, found pattern class <space> then read the immediate character following class <space>, it was uppercase 'C', implies test OK. Test fails for the second line. Basically, set a bash variable, say test, to FALSE if test fails otherwise TRUE. How do I do this using awk, sed, or grep?

1

This is equally straight-forward in any of the three tools you mentioned (awk, sed, or grep) or using any other tool which has support for regular expressions. Here's a regular expression that matches the pattern that you want:

'^\s*class [A-Z]'

It matches an arbitrary amount of white-space at the beginning of the line, followed by the string class, followed by an upper-case letter. You could apply it by using it in this (partial) grep command:

grep -Pq '^\s*class [A-Z]'

To test it out, you could try something like the following:

user@host:~$ \
if echo '    class Camel' | grep -Pq '\s*class [A-Z]'; then \
    echo TRUE; \
else \
    echo FALSE; \
fi

TRUE

user@host:~$ \
if echo '    class camel' | grep -Pq '\s*class [A-Z]'; then \
    echo TRUE; \
else \
    echo FALSE; \
fi

FALSE

If you want to store the result in the variable TEST then you could do something like the following:

if echo '    class camel' | grep -Pq '\s*class [A-Z]'; then \
    TEST=TRUE; \
else \
    TEST=FALSE; \
fi
1

To read the content of a file you can use the cat command to display the file and then divert its output to other command input. The below is simple regular expression which matches your basic requirement.

cat hello | grep '^\s*class [A-Z]'

Description :

'cat hello'

This displays the content of the file.

'|'

This is called pipe. Which directs first command output to next command input.

'grep'

Grep command is used to do pattern matching.

'^\s*class [A-Z]'

The above line describes your requirement to match the upper case letter after the word class. That is called pattern matching.

This is a good source to learn regular expressions regular expresion

Thank you.

  • Your regular expression '^\sclass [A-Z]' matches exactly one white-space character. You probably want this instead: '^\s*class [A-Z]' – igal Dec 7 '17 at 13:48
  • UUOC (useless use of cat). Just pass the filename as the final argument to grep. – m0dular Dec 7 '17 at 18:24
  • Yes, even that method is also possible. @m0dular – Susarla Nikhilesh Dec 7 '17 at 18:25

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.