linux - 在不知道目录名称的情况下打开目录

标签 linux bash shell directory-listing

我正在编写一个脚本,用户在其中输入他想要在 .txt 文件中查找特定字符串的目录,但我不知道如何在不知道其名称的情况下打开给定目录中的每个目录。

例如,这是用户指定的目录:

Project/
   AX/include/
             ax.txt
             bx.txt
   AX/src/
         ax.txt
         bx.txt
   BY/include/
             ay.txt
             by.txt
   BY/src/
         ay.txt
         by.txt

最佳答案

只需使用 grep -r递归地查找文件中的字符串。你不应该重新发明轮子。在您的情况下运行 grep -r "string to find"Project/

也就是说,要列出文件夹 path/to/folder/ 中的文件夹,您只需让 shell 使用通配符来扩展它,如 ls path/to/folder/*/ 。所以你只需要运行 yourcommand path/to/folder/*/

或者使用find :

find path/to/folder/ -type d -maxdepth 1 -exec yourcommand {} + # or
find path/to/folder/ -type d -maxdepth 1 -print0 | xargs -z yourcommand

要在更多级别中执行此操作,请在启用 globstar 后使用 find path/to/folder/-type d -exec yourcommand {} +yourcommand path/to/folder/**/*/shopt -s globstar

关于linux - 在不知道目录名称的情况下打开目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59510604/

相关文章:

linux - 在 VPS 服务器上 24/7 在后台运行特定的 ssh 命令

linux - 我对以下示例的重定向操作持怀疑态度

bash - 在一组文件中查找文本的更简洁的方法是什么?

bash - 在 bash 脚本中将通配符作为参数替换到文件路径后如何扩展通配符?

linux - shell脚本用于在linux中打开文件夹中的不同文件

linux - 用环境变量替换curl请求中的变量

c++ - 如何设置qwt路径或环境变量

bash - 使用 sed 省略最后一行

Perl 的菱形运算符 : can it be done in bash?

python - 无法从 Eclipse 中的 Pydev 环境运行 shell 脚本