1

I have a bunch of files, where template tags are used. I want to list all the different template tags used in all of the files.

This is my used bash script, which gives no match...

for f in EHS/*.html;  do
  value=`cat ${f}`;
  [[ $value =~ "({%.*?%})" ]]
  if [[ ${BASH_REMATCH[0]} ]]; then
    echo "Found: ${BASH_REMATCH[0]}";
  fi
done;

This is a snippet from one of the html files:

<p>
  The ordernumber is: {%OrderNumber%}<br>
  The partnumer is: {%PartNumber%}
</p>

So my goal is to just return all of the different tags used...

4
  • $value is just one big string containing all the html... Commented Jul 12, 2018 at 12:05
  • 1
    I think grep -o "{%[^%]*%}" would be more natural to get all the matches like that from the file. In Bash, it is combersome to extract multiple matches. Commented Jul 12, 2018 at 12:06
  • Seems to work :) Can you explain the difference with my regular expression? Commented Jul 12, 2018 at 12:11
  • 1
    Bash regex does not support lazy quantifiers, and when you quote the pattern after =~ inside [[...]], literal string matching is triggered, it is not regarded as a regex. You could use if [[ $s =~ \{%[^%]*%} ]]; but you will find a single match only. Commented Jul 12, 2018 at 12:15

1 Answer 1

4

Two problems:

  1. The regex should be unquoted, but {} needs escaping, as their meaning is special.

  2. bash doesn't support frugal quantifiers like *?.

It's easier to use grep:

grep -o '{%[^}]*%}'

The -o option only returns the matching parts, one per line.

Note that strings like {%ab%cd}ef%} aren't matched as there's no easy way how to prevent parts of multicharacter delimiters in standard grep. With pgrep, you can use

grep -o -P '{%.*?%}'

as you originally intended.

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

Comments

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.