-1

I'm searching a directory (and deeper directories) for twig files that have variables {{ something var name }} and I would like to output into a file (twig-vars.txt).

Maybe using grep and regex? This is not my wheelhouse, so thanks in advance!

Example output (twig-vars.txt):

{{ somevar }}
{{ someothervar }}
{{ site.url }}
{{ ... }}
n8tron
  • 109
  • 9

1 Answers1

0

With grep in PCRE mode:

grep -oP '{{\s*\K[\w.]+' file
-------8<------------------
somevar
someothervar
site

Or with Perl:

perl -nE 'say $& if/{{\s*\K[\w.]+/' file
-------8<------------------
somevar
someothervar
site

The regular expression matches as follows:

Node Explanation
{{ '{{'
\s* whitespace (\n, \r, \t, \f, and " ") (0 or more times (matching the most amount possible))
\K resets the start of the match (what is Kept) as a shorter alternative to using a look-behind assertion: look arounds and Support of K in regex
[\w.]+ any character of: word characters (a-z, A- Z, 0-9, _), '.' (1 or more times (matching the most amount possible))

Or with awk

awk -F'{{ | }}' '{print $2}' file
-------8<------------------
somevar
someothervar
site.url
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • thx so much, but I'm getting `grep: invalid option -- P` -- I'm on a new Mac btw. thoughts? – n8tron Jan 19 '23 at 16:54
  • When I run these commands `awk` or `pearl` in the directory of the twig files, I don't get any output. "twig-vars.txt" 0L, 0B touch file awk -F'{{ | }}' '{print $2}' file empty file. – n8tron Jan 19 '23 at 17:02
  • 1
    Oh -- it would be something like `awk -F'{{ | }}' '{print $2}' * > twig-vars.txt` – n8tron Jan 19 '23 at 17:23
  • One more thing -- This script isn't picking up `{{ site.url }}`. thoughts? I need `{{ }}` thanks btw! – n8tron Jan 19 '23 at 17:53
  • @n8tron : better to escape the `{` and `}`, otherwise `gawk --posix` mode would act up : `echo '{{ somethingvar }}' | gawk -F'{{ | }}' --posix '{print $2}'` :::::::: |> `gawk: fatal: invalid regexp: Invalid preceding regular expression: /{{ | }}/` ::::::::: `echo '{{ somethingvar }}' | gawk -F'[{][{] | [}][}]' --posix '{print $2}'` |> `somethingvar` – RARE Kpop Manifesto Jan 20 '23 at 13:37