What I'm trying to accomplish:

Search for the regular expression \b\$\w+ in all .php files that fall under this directory structure:


Edit: I should state that my higher-level goal is to find unique PHP variables within files

What I tried:

grep '\b\$\w+' **/templates/*.php
grep '\b\$\w+' */templates/*.php
grep '\b\$\w+' **/templates/**.php

None of them seem to produce the expected results. What is the correct syntax to do this?

Additionally it would be nice to "group by" or "select distinct" (so for instance $_GET would only show up once even if there's 180 instances in the file) if that's possible.

I've already read these answers which led me to try the above commands:



grep -oE '\$\w+' */templates/*.php | sort -u


  • The -o option tells grep to print only the matching portions of the line, not the whole line. This should give you the names of all $-style variables.

  • sort -u sorts and removes duplicates so each variable name should appear in the output only once.

  • The \w construct that you were using requires extended regex. Therefore, the -E option was added.

  • The use of \b for word boundaries is problematic here because $ is not a valid "word" character and hence does not begin a word as \b would understand it. Therefore, \b would only match if a word happened to end just before the $ as in a$b but not a $b. \b was removed from the code above.

  • Do you happen to know which package sort is in so I can install it via apt-get? I'm using Linux Mint – rink.attendant.6 Sep 14 '14 at 22:54
  • @rink.attendant.6 Mint is part of the Debian family. On Debian, /usr/bin/sort is in coreutils. So use: apt-get install coreutils. coreutils, being core utilities, though, really should be installed by default. As it says on LinuxMint.com: "This package contains the basic file, shell and text manipulation utilities which are expected to exist on every operating system." – John1024 Sep 14 '14 at 23:09

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.