【问题标题】:How to use "which" with regex, or other ways to find a command in the $PATH如何将“which”与正则表达式一起使用,或以其他方式在 $PATH 中查找命令
【发布时间】:2018-06-22 07:31:02
【问题描述】:
我正在寻找一个命令,我想使用正则表达式来找到它。
所以,像这样的
>>> which -a "e?grep"
/bin/grep
/bin/egrep
也感谢任何解决方法。
【问题讨论】:
标签:
linux
bash
shell
unix
command-line
【解决方案1】:
正如另一个问题中所述,您可以使用compgen 来list all commands and functions,从而使任务成为您想要使用哪个正则表达式引擎或命令的小事。
列出您可以运行的所有内容的示例:
$ compgen -A function -abck | grep '.*grep.*'
egrep
fgrep
grep
egrep
fgrep
grep
lzfgrep
fgrep
lzgrep
zstdgrep
zfgrep
bzgrep
plugreport
pcregrep
lzegrep
msggrep
grep
pgrep
zegrep
zgrep
egrep
xzegrep
zipgrep
xzgrep
xzfgrep
pcre2grep
orc-bugreport
ptargrep
ptargrep
有关更多信息和其他可用列表,请参阅提到的问题。归功于用户 Rahul Patil。
【解决方案2】:
只需搜索$PATH变量:
find $(tr : ' ' <<<"$PATH") -type f -executable | egrep "/[e]?grep$"
首先我在 PATH 目录中找到所有可执行文件,然后使用您的正则表达式进行 egrep。
命令输出:
/usr/bin/egrep
/usr/bin/grep
【解决方案3】:
这个答案扩展了Kamil Cuk's idea。改进:
- 支持
$PATH 包含空格和换行符。
- 不要不要搜索
$PATH的子目录。
脚本:
#! /bin/bash
# Search a program using an extended regex.
# usage: thisScript extendedRegex
IFS=: read -d '' -a patharray < <(printf %s "$PATH")
find "${patharray[@]}" -maxdepth 1 -type f -executable \
-regextype egrep -regex ".*/$1"
您的正则表达式必须匹配整个命令名称,类似于grep -x。
可能的变化:
- 若要同时匹配部分命令名称,请将
-regex ".*/$1" 更改为-regex ".*/.*$1.*"。但是,^ 和 $ 将不适用于此更改。
- 对于不区分大小写的搜索,请将
-regex 更改为 -iregex。
- 要使用另一种正则表达式样式,请相应地更改
egrep。 find -regextype help 打印所有支持的正则表达式类型。
- 要仅打印命令名称而不是完整路径,请附加
-printf '%f\n'。