代码之家  ›  专栏  ›  技术社区  ›  Hielke Walinga

如何将“which”与regex一起使用,或以其他方式在$path中查找命令

  •  1
  • Hielke Walinga  · 技术社区  · 7 年前

    我正在寻找一个命令,我想使用regex来查找它。

    所以,像这样的事情

    >>> which -a "e?grep"
    /bin/grep
    /bin/egrep
    

    任何解决办法也值得赞赏。

    3 回复  |  直到 7 年前
        1
  •  1
  •   badc0de    7 年前

    如另一个问题所述,你可以 list all commands and functions 使用 compgen 这样,任务就成了你想使用的正则表达式引擎或命令的一个小问题。

    一个列出您可以运行的所有内容的示例:

    $ 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
  •  1
  •   KamilCuk    7 年前

    只是找进去 $PATH 变量:

    find $(tr : ' ' <<<"$PATH") -type f -executable | egrep "/[e]?grep$"
    

    首先在路径目录中找到所有可执行文件,然后使用regex导出。
    命令输出:

    /usr/bin/egrep
    /usr/bin/grep
    
        3
  •  0
  •   Socowi    7 年前

    这个答案延伸了 Kamil Cuk's idea 。改进:

    • 支持 $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 .
    • 要使用其他regex样式,请更改 egrep 因此。 find -regextype help 打印所有支持的正则表达式类型。
    • 要只打印命令名而不是完整路径,请附加 -printf '%f\n' .