为什么在find命令中使用dirname为每个匹配提供点? [英] Why using dirname in find command gives dots for each match?

查看:235
本文介绍了为什么在find命令中使用dirname为每个匹配提供点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 找到`pwd`找到一个任务,我注意到当我做这样的事情时: -namefile.ext-exec echo $(dirname {})\; 

每个比赛只会给你点数。如果在该命令中将 dirname 替换为 basename ,则会得到完整的路径名。我在这里搞了些什么,或者是这个预期的行为?我习惯于 basename 给你文件的名称(在这种情况下 file.ext )和 dirname 给你剩下的路径。

解决方案

考虑下面的脚本:

 #!/ bin / sh 
set -x
找到`pwd` -name文件。 ext-exec echo $(dirname {})\;

set -x 最后的命令是什么运行时,输出如下:

pre $ $ $ $ $ $ b $ d $ $ $ $ b + find / home / kibab -name file.ext -exec echo。 ';'

所以,扩展的第一件事是 pwd 。其次是 $(dirname {})。这两个命令的结果被放到find命令中。因此,你告诉找到 -exec echo。,所以你看到了预期的输出。



当用 basename 代替 dirname 时,扩展仍然存在,但是扩展的结果是不同的: p>


  1. pwd 展开为当前路径。在上面的例子中,结果是 / home / kibab

  2. basename {} 执行。这个命令的结果是 {}

  3. find命令执行上面的替换。最后执行的命令如下所示:

    find / home / kibab -name'* .png'-exec echo'{}''; '


在检查上述命令后,您会注意到echo



$ p $也许你想要这样的东西?

  find`pwd` -namefile.ext-printf%f\\\


I'm using find for a task and I noticed that when I do something like this:

find `pwd` -name "file.ext" -exec echo $(dirname {}) \;

it will give you dots only for each match. When you substitute dirname with basename in that command you get the full pathnames. Am I screwing something up here or is this expected behavior? I'm used to basename giving you the name of the file (in this case file.ext) and dirname giving you the rest of the path.

解决方案

Consider the following script:

#!/bin/sh
set -x
find `pwd` -name "file.ext" -exec echo $(dirname {}) \;

set -x shows how the expansion works and what the final command is. When run, it gives the following output:

++ pwd
++ dirname '{}'
+ find /home/kibab -name file.ext -exec echo . ';'

So, the first thing that is expanded is the pwd. Second is $(dirname {}). The result of those two commands is then dropped into the find command. Thus, you're telling find to -exec echo ., so you're seeing the expected output.

When you substitute basename for dirname, the expansion still takes places, but the results of the expansion are different:

  1. pwd is expanded to the current path. In my example above, the result is /home/kibab
  2. basename {} is executed. The result of this command is {}.
  3. The find command is executed with the above substitutions in place. The final command executed looks like this:

    find /home/kibab -name '*.png' -exec echo '{}' ';'

Upon inspecting the above command, you'll notice that the command now simply echo's whatever file was found.

Perhaps you want something like this?

find `pwd` -name "file.ext" -printf "%f\n"

这篇关于为什么在find命令中使用dirname为每个匹配提供点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆