2

Trying to match any string that looks like {% extends "file.txt" %}, using the following code:

local FILE_REG="(\.{0,2}\/)*([a-zA-Z0-9_]*|\/[a-zA-Z0-9_]*)*[a-zA-Z0-9_]*\.[a-zA-Z0-9_]*"
local EXTENDS_REG='{%\s*extends\s*".*"\s*%}'

local extends=0
local filename="$1"

echo $EXTENDS_REG;
while read -r line ; do
  if [[ "$line" =~ "{%\s*extends\s*\".*\"\s*%}" ]] ; then
    echo "true: $line";
  else
    echo "false: $line";
  fi;
done < $filename

The if statement fails to return true on the first line of the following:

{% extends "base.tsh" %}
{% block my_block %}
  echo "Hello World from inherit.tsh!"
{% endblock %}

I have verified my regex on regex101.com and the pattern on line 2 matches the string perfectly, while replacing the ".*" by $FILE_REG matches the previous string with "file.txt" being replaced by any valid /path/to/file_with_extension.txt.

I have tried numerous variations of the EXTENDS_REG in the if statement, including:

  • if [[ "$line" =~ "$EXTENDS_REG" ]] (variable)
  • if [[ "$line" =~ $EXTENDS_REG ]] (variable, no quotes)
  • if [[ "$line" =~ '{%\s*extends\s*".*"\s*%}' ]] (single quotes around regex)
  • if [[ "$line" =~ '{%\s*extends\s*"'$FILE_REG'"\s*%}' ]] (composite + single quotes)
  • if [[ "$line" =~ {%\s*extends\s*\".*\"\s*%} ]] (no quotes)

but none have worked. I suspect the if regex match to be too limited to read the regex properly within bash.

Anyone has any solution? Optimally I am looking for something efficient, and that does not rely on external binaries except grep, awk, sed and al. No python, ruby, perl, etc. please ;)

Thanks for your help!

1 Answer 1

4
line='{% extends "file.txt" %}'
if [[ $line =~ \{%[[:space:]]*extends[[:space:]]*\".*\"[[:space:]]*%\} ]]

In bash replace character classes such as \s with those of the form [[:class:]].

Here's a definitive list.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, would never have found that out myself. +1 for the source too. Would you know why using your version of the regex in a variable doesn't work? Aka EXTEND_REG=\{%[[:space:]]*extends[[:space:]]*\".*\"[[:space:]]*%\} and [[ $line =~ "$EXTEND_REG" ]] or [[ $line =~ $EXTEND_REG ]]? Is it because the $ conflicts with the regex eval?
Try EXTEND_REG='\{%[[:space:]]*extends[[:space:]]*\".*\"[[:space:]]*%\}' and then [[ $line =~ $EXTEND_REG ]]
It works indeed! Thanks that will allow me to make my code cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.