文件搜索 bash 脚本
我正在尝试制作一个非常简单的 bash 脚本来查找当前目录的目录结构中与给定名称匹配的文件。因此,我使用了这样的 find 函数,
ARGS=1
E_BADARGS=65
E_NOFILE=66
if [ $# -ne "$ARGS" ] # Correct number of arguments not passed
then
echo "Usage: `basename $0` filename"
exit $E_BADARGS
fi
echo `find ./ -type f -name \$1`
效果很好,但与我在命令行中使用 find 命令时不同,生成的文件路径不是用换行符分隔,而是用空格分隔。这在屏幕上自然不太容易看到。我如何回显以便它找到的每个文件都以换行符分隔。
i am trying to make a very simple bash script to find files matching the given name in the directory structure of the current directory. So, I used the find function like this
ARGS=1
E_BADARGS=65
E_NOFILE=66
if [ $# -ne "$ARGS" ] # Correct number of arguments not passed
then
echo "Usage: `basename $0` filename"
exit $E_BADARGS
fi
echo `find ./ -type f -name \$1`
this works fine but unlike when I use the find command in the command line, the resulting file paths are not separated by newline but just by a space. This naturally isn't too easy to see in the screen. How can I echo so that each file it finds will be separated by a newline.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会将您的 find 命令更改为:
find 。 -maxdepth 1 -type f -name "$1"
请注意,双引号在 find 命令中非常重要,可以正确处理正则表达式。我还添加了
maxdepth 1
来仅搜索当前目录中的文件I would change your find command to this one:
find . -maxdepth 1 -type f -name "$1"
Note that the double quotes are kind important in find command, to treat regular expressions correclty. Also I added
maxdepth 1
to search files only in the current directory正如 @codaddict 指出的,这里不需要
echo
。但这也是理解代码为何以这种方式运行的一个很好的练习。提示:比较和
As @codaddict noted,
echo
is unnecessary here. But it's also a good exercise to understand why does your code behave in such a way. Hint: compareand
尝试更改
为
Try changing
to