Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i get main folder name inside root folder while copying all files to source to destination

i have folders inside input_scan but i need folder1 and folder3 beacuse they are super folders for 5.txt,1.txt and 2.txt. how can i get this? with the current code i am getting folder1 for 5.txt, folder2 for 1.txt and folder7 for 2.txt

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)

like image 830
lemon chow Avatar asked Nov 29 '25 17:11

lemon chow


1 Answers

With GNU utils.

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

If it is a shell loop.

#!/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[@]}"

Since there is no need to count the directories, we can change

((uniq["${dir%%/*}"]++))

To:

uniq["${dir%%/*}"]=
like image 56
Jetchisel Avatar answered Dec 02 '25 07:12

Jetchisel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!