Using a glob pattern as an argument to “which”

whichwildcards

Is it possible to use the which command on a glob pattern to return multiple results?

For example, I want to know the full path of all my latex commands. I can try:

[lucas@lucas-ThinkPad-W520]/home/lucas$ which latex
/usr/bin/latex

or:

[lucas@lucas-ThinkPad-W520]/home/lucas$ which pdflatex 
/usr/bin/pdflatex

or:

[lucas@lucas-ThinkPad-W520]/home/lucas$ which xelatex 
/usr/bin/xelatex

but I cannot use:

[lucas@lucas-ThinkPad-W520]/home/lucas$ which *latex

which returns nothing.

Any suggestions on how to use a glob pattern with the which command?

Best Answer

With zsh (note that which is only built in tcsh or zsh, in other shells it can give random results, use type in Bourne like shells):

$ which -m '*latex'
/usr/bin/arlatex
/usr/bin/dvilualatex
/usr/bin/fig4latex
/usr/bin/latex
/usr/bin/lualatex
/usr/bin/pdflatex
/usr/bin/pod2latex
/usr/bin/pslatex

Or (if you only want to consider executables and not functions, aliases...):

$ ls -ld $^path/*latex(-*DN)
lrwxrwxrwx 1 root root    53 Apr  8 03:14 /usr/bin/arlatex -> ../share/texlive/texmf-dist/scripts/bundledoc/arlatex*
lrwxrwxrwx 1 root root     6 Apr  8 03:51 /usr/bin/dvilualatex -> luatex*
lrwxrwxrwx 1 root root    55 Apr  8 03:51 /usr/bin/fig4latex -> ../share/texlive/texmf-dist/scripts/fig4latex/fig4latex*
lrwxrwxrwx 1 root root     6 Apr  8 03:51 /usr/bin/latex -> pdftex*
lrwxrwxrwx 1 root root     6 Apr  8 03:51 /usr/bin/lualatex -> luatex*
lrwxrwxrwx 1 root root     6 Apr  8 03:51 /usr/bin/pdflatex -> pdftex*
-rwxr-xr-x 1 root root 10340 May 20  2013 /usr/bin/pod2latex*
lrwxrwxrwx 1 root root    54 Apr  8 03:14 /usr/bin/pslatex -> ../share/texlive/texmf-dist/scripts/texlive/pslatex.sh*

With other Bourne-like shells, you could do:

searchPATH() (
  pattern=$1
  IFS=:; set -f; set -- $PATH
  set +f; IFS=
  for i do
    for j in "$i"/$pattern; do
      [ -x "$j" ] && printf '%s\n' "$j"
    done
  done
)

And then:

$ searchPATH '*latex'
/usr/bin/arlatex
/usr/bin/dvilualatex
/usr/bin/fig4latex
/usr/bin/latex
/usr/bin/lualatex
/usr/bin/pdflatex
/usr/bin/pod2latex
/usr/bin/pslatex

That should work more the most common values of $PATH. It will omit the entries in the current directory if $PATH ends in : (like /bin:/usr/bin:)