首页 > 解决方案 > 如何在shell中递归查找文件

问题描述

我正在尝试以下内容:

find /dir1/dir2/dir3 -name '*.txt' -type f

我想要做的是我想在 dir3 文件夹中递归搜索文件。这意味着在 dir3 下有 dir4 和 dir5 文件夹,我希望应该从 dir4 和 dir5 目录返回与 *txt 扩展名匹配的文件。另外,如何获取仅在今天创建的文件?

标签: shell

解决方案


假设你使用 bash,我想出了这个:

#!/bin/bash

# This depends on your systems locale I think.
# for me, `date` returns `So 25. Jul 12:32:27 CEST 2021`.
# Therefore I want the $2 for DAY and $3 for MONTH, yours might be different.
DAY="$(date | awk '{print $2}')" 
MONTH="$(date | awk '{print $3}')"
FINDIN="/dir1/dir2/dir3"

# This prints only `.txt` files which were created today along with all their details.
# If you only want the path, you could pipe it into
# `awk '{print $11}'`
find "$FINDIN" -type f -ls | grep -E "*.txt$" | grep "$MONTH $DAY"

使用 bashisms,你可以在技术上使它成为一个(冗长的)单行,但如果你把它放在一个脚本中,你可以用你的路径($FINDIN)代替作为参数($1,,$2...)或调用者目录(隐含 /解析自$0)。


推荐阅读