文件搜索 bash 脚本

发布于 2024-09-19 19:38:27 字数 392 浏览 6 评论 0原文

我正在尝试制作一个非常简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情绪操控生活 2024-09-26 19:38:27

我会将您的 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

安静 2024-09-26 19:38:27

正如 @codaddict 指出的,这里不需要 echo 。但这也是理解代码为何以这种方式运行的一个很好的练习。提示:比较

echo  `find ./ -type f -name \$1`

echo  "`find ./ -type f -name \$1`"

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: compare

echo  `find ./ -type f -name \$1`

and

echo  "`find ./ -type f -name \$1`"
十雾 2024-09-26 19:38:27

尝试更改

echo  `find ./ -type f -name \$1`

find ./ -type f -name $1

Try changing

echo  `find ./ -type f -name \$1`

to

find ./ -type f -name $1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文