我正在编写一个脚本,用户在其中输入他想要在 .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/