如何在将所有文件复制到源到目标时获取根文件夹中的主文件夹名称

问题描述 投票:0回答:2

我在 input_scan 中有文件夹,但我需要 folder1 和 folder3,因为它们是 5.txt、1.txt 和 2.txt 的超级文件夹。我怎样才能得到这个?使用当前代码,我得到 5.txt 的 folder1,1.txt 的 folder2 和 2.txt 的 folder7

Ex:
input_scan
 /folder1
   /5.txt
   /folder2
     /1.txt
 /folder3
  /folder4
   /folder5
    /folder6
      /folder7
       /2.txt


while IFS= read -r -d '' file; do
    if [ -f "$file" ]; then
        parent_dir=$(basename "$(dirname "$file")")
        echo $parent_dir
    fi
done < <(find "input_scan" -type f -print0)

bash shell file unix
2个回答
0
投票

使用 bash 和 GNU 查找:

$ mapfile -d '' supers < <(
    find input_scan/* \
        -type d \
        -exec find {} -type f -quit \; \
        -printf '%f\0' \
        -prune
)

现在

supers
是一个包含目录的bash数组。

  • input_scan/*
    - 可能的目录列表
  • -type d
    - 忽略非目录
  • -exec find ...
    - 如果包含任何文件则为真
  • %f
    - 路径的基本名称(即我们想要的目录名称)
  • -prune
    - 只处理顶层
  • mapfile -d ''
    - 将空分隔值读入数组

0
投票

使用 GNU 工具。

find "input_scan" -type f -print0 | cut -zd'/' -f2 | sort -zu 

如果是shell循环

#!/usr/bin/env bash

declare -A uniq
while IFS= read -rd '' file; do
  dir=${file#*/}
  ((uniq["${dir%%/*}"]++))
done < <(find "input_scan" -type f -print0)
printf '%s\n' "${!uniq[@]}"
© www.soinside.com 2019 - 2024. All rights reserved.