【问题标题】:find command - get base name only - NOT with basename command / NOT with printffind 命令 - 仅获取基本名称 - 不使用 basename 命令/不使用 printf
【发布时间】:2023-02-02 20:44:07
【问题描述】:

有没有办法在命令find中得到basename

什么我需要:

  • find /dir1 -type f -printf "%f\n"
  • find /dir1 -type f -exec basename {} \;

为什么你会问?因为我需要继续使用found file。我基本上想要这样的东西:

find . -type f -exec find /home -type l -name "*{}*" \;

它使用./file1,而不是file1作为-name的参数。

【问题讨论】:

  • find /dir1 -type f -printf "%f\n" 工作正常,有什么问题吗?
  • 你是什​​么意思我需要继续使用找到的文件?如果您需要基本名称abs 路径也是如此,只需将 abs 路径通过管道传输到您选择的程序中,然后在那里执行逻辑。或者不使用 find,而是使用显式循环 (for f in /dir1/**)环球之星打开。当然你必须处理测试普通文件由你自己。

标签: bash shell find


【解决方案1】:

生成一个 shell 并进行第二次调用以从那里查找

find /dir1 -type f -exec sh -c '
for p; do
  find /dir2 -type l -name "*${p##*/}*"
done' sh {} +

如果您的文件名称中可能包含特殊字符(如[? 等),您可能希望像这样转义它们以避免误报

find /dir1 -type f -exec sh -c '
for p; do
  esc=$(printf "%sx
" "${p##*/}" | sed "s/[?*[]/\&/g")
  esc=${esc%x}
  find /dir2 -type l -name "*$esc*"
done' sh {} +

【讨论】:

    【解决方案2】:

    简单地生成一个bash shell:

    find /dir1 -type f -exec bash -c '
        base=$(basename "$1")
        echo "$base"
        do_something_else "$base"
    ' bash {} ;
    

    $1中的bash部分是find过滤的每个文件。

    【讨论】:

      【解决方案3】:

      您必须将其转发给另一位评估员。 find 现在有办法做到这一点。

      find . -type f -printf '%f
      【解决方案4】:

      如果你有 Bash 版本 4.3 或更高版本,试试这个Shellcheck-clean 纯 Bash 代码:

      #! /bin/bash -p
      
      shopt -s dotglob globstar nullglob
      for path in ./**; do
          [[ -L $path ]] && continue
          [[ -f $path ]] || continue
          base=${path##*/}
          for path2 in /home/**/*"$base"*; do
              [[ -L $path2 ]] && printf '%s
      ' "$path2"
          done
      done
      
      • shopt -s ... 启用代码所需的一些 Bash 设置:
        • dotglob 使 glob 能够匹配以 . 开头的文件和目录。 find 默认显示此类文件。
        • globstar 允许使用 ** 通过目录树递归匹配路径。 globstar 是在 Bash 4.0 中引入的,但在 Bash 4.3(2014)之前使用它是危险的,因为它在查找匹配项时遵循符号链接。
        • nullglob 使 glob 在没有匹配项时扩展为空(否则它们扩展为 glob 模式本身,这在程序中几乎没有用)。
      • 有关${path##*/} 的解释,请参阅Removing part of a string (BashFAQ/100 (How do I do string manipulation in bash?))。这总是有效的,即使在$(basename "$path") 无效的极少数情况下也是如此。
      • 请参阅对Why is printf better than echo? 的已接受且优秀的回答,以了解为什么我使用printf 而不是echo 来输出找到的路径。
      • 如果您的文件名称中包含模式字符(?*[]),则此解决方案可以正常工作。

      【讨论】:

        猜你喜欢
        • 2016-01-06
        • 2016-05-13
        • 1970-01-01
        • 1970-01-01
        • 2021-01-06
        • 1970-01-01
        • 2016-11-14
        • 2016-05-29
        • 2021-06-07
        相关资源
        最近更新 更多