【问题标题】:How to find basename of path via pipe如何通过管道查找路径的基本名称
【发布时间】:2019-06-09 03:50:52
【问题描述】:

这不起作用:

find "$all_locks" -mindepth 1 -maxdepth 1 -type d | basename

显然 basename 无法从标准输入读取 - 在任何情况下,basename 至少需要一个参数。

【问题讨论】:

  • 您只是想去掉最终的目录名称,还是想从$all_locks 中找到可能是符号链接的事物的父项?
  • 我只是想获取 find 产生的每个路径的基本名称
  • 所以如果/path/to/this/some/other/place的符号链接,你的结果应该是/path/to还是/some/other

标签: bash shell find basename


【解决方案1】:

这里的问题是basename 不接受stdin,因此未命名的管道可能没有用。我想稍微修改一下你的命令。让我知道它是否达到目的。

find -mindepth 1 -maxdepth 1 -type d -exec basename {}  \;

注意:没有足够的声誉来发表评论,因此在此处发布。

【讨论】:

  • 在 ubuntu bash 4 上,我得到 find: missing argument to '-exec'...奇怪
  • @MrCholo,我希望你没有错过 {} 和 \ 之间的空格?因为,我可以通过擦除那个空间来重现你的问题。
【解决方案2】:

要将命令应用于管道操作的每个结果,xargs 是您的朋友。正如它在我链接的手册页上所说的那样......

xargs 从标准输入读取项目,由空格分隔( 可以用双引号或单引号或反斜杠保护)或 换行符,并执行一个或多个命令(默认为 /bin/echo) 带有任何初始参数的时间,后跟从标准读取的项目 输入。

在这种情况下,这意味着它将从您的 find 命令获取每个结果并运行 basename <find result>ad nauseum,直到 find 完成搜索。我相信你想要的看起来很像这样:

find "$all_locks" -mindepth 1 -maxdepth 1 -type d | xargs basename

【讨论】:

    【解决方案3】:

    由于 mindepthmaxdepth 是 GNU 扩展,使用诸如 printf 之类的另一个扩展不会降低其可移植性。

    find "$all_locks" -mindepth 1 -maxdepth 1 -type d -printf '%f\n'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-31
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多