在目录中搜索文件

时间:2014-03-18 16:50:27

标签: bash

我有2个关于该主题的问题:

  1. 我需要在目录中搜索文件c.txt,我知道if [[ -f c.txt ]]会在脚本运行的当前目录中搜索它,但我该如何搜索某个目录,例如dir1,文件a.txt?

  2. 这样它还会搜索所有子目录吗?例如:如果dir1不包含a.txt但它的dir2包含c.txt,我会得到true还是false?

1 个答案:

答案 0 :(得分:0)

这将找到所有名为a.txt的文件

find -type f -name a.txt

这将找到所有名为[something] .txt

的文件
find -type f -name *.txt

如果您想要返回值而不是找到的文件的输出,请使用

find -type f -name *.txt >/dev/null
[[ $? == 0 ]] && echo "FILE FOUND" || echo "FILE NOT FOUND"

您可以使用find -exec进行更多测试甚至获得更多乐趣... 有关更多信息,请使用

man find  

编辑:当您不被允许使用find时,请使用此

测试是dir1中存在a.txt

[[ -f "/full/path/to/file/dir1/a.txt" ]]

并测试dir1或dir2中是否存在a.txt或c.txt

[[ -f "/full/path/to/file/dir1/a.txt" || -f "/full/path/to/file/dir2/c.txt" ]] && echo "a.txt or c.txt exist!" || echo "neither a.txt nor c.txt exist"
相关问题