代码之家  ›  专栏  ›  技术社区  ›  Mainland

Linux在子目录和.js.py文件中搜索特定关键字

  •  0
  • Mainland  · 技术社区  · 3 年前

    我正试图在从开始的所有子目录中搜索具有特定关键字的文件/脚本 root home directory 。我的搜索产生了很多文件,但我只想搜索 .js , .py 类型。我想知道包含此的文件名 matching word .

    grep -name '*.js' -rl "matching word" ./
    

    当前输出:

    grep: invalid max count
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   John3136    3 年前

    这里有一种方法:

    find start_dir -type f \( -name "*.js" -o -name "*.py" \) -exec grep -l "word" {} \;
    

    它将在起始目录中或其下找到所有.js或.py文件,然后对给定单词进行grep。还有其他方法,但这是我对这类事情的“首选”。

        2
  •  1
  •   Sundeep    3 年前

    您可以使用 --include 基于glob模式过滤文件的选项。对于多个球体,可以多次使用此选项,也可以使用支撑展开功能。

    echo --include={*.js,*.py} #expands to: --include=*.js --include=*.py
    grep -rl --include={*.js,*.py} 'matching word'
    
    # use this if you can have files that can start with '--include'
    grep -rl --include='*.js' --include='*.py' 'matching word'
    

    另一种选择是利用 globstar 功能(假设您没有与globs匹配的文件夹,否则您将不得不使用 -d skip 以防止目录被视为要搜索的文件)。

    shopt -s globstar
    grep -l 'matching word' **/*.js **/*.py