Milkmannetje
Milkmannetje

Reputation: 1182

Find strings in files with regex in bash

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...

Upvotes: 1

Views: 9762

Answers (1)

choroba
choroba

Reputation: 241848

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.

Upvotes: 4

Related Questions