I have a folder with a complicated folder structure:

├── folder1
│   ├── 0001.jpg
│   └── 0002.jpg
├── folder2
│   ├── 0001.jpg
│   └── 0002.jpg
├── folder3
│    └── folder4
│         ├── 0001.jpg
│         └── 0002.jpg
└── folder5
     └── folder6
           └── folder7
                ├── 0001.jpg
                └── 0002.jpg   

I would like to flatten the the folder structure such that all the files reside in the parent directory with unique names such as folder1_0001.jpg, folder1_0002.jpg etc.

I have attempted to use the code suggested in "Flattening folder structure"

$ find */ -type f -exec bash -c 'file=${1#./}; echo mv "$file" "${file//\//_}"' _ '{}' \;

The echo demonstrates that it is working:

mv folder3/folder4/000098.jpg folder3_folder4_000098.jpg

But the output files are not placed in the parent directory and I have searched the drive cannot be found the output files.

I have also attempted "Flatten a folder structure to a file name in Bash"

$ find . -type f -name "*.jpg" | sed 'h;y/\//_/;H;g;s/\n/ /g;s/^/cp -v /' | sh

-v demonstrates that it is working:

‘./folder3/folder4/000098.jpg’ -> ‘._folder3_folder4_000098.jpg’

However the output creates hidden files in the parent directory, this complicates my workflow. I am able to view these hidden files in the parent directory using ls -a

I have also tried the suggested code below from "Renaming Duplicate Files with Flatten Folders Command"

find . -mindepth 2 -type f | xargs mv --backup=numbered -t . && find . -type d -empty -delete

But the command overwrites files with similar file names.

Any suggestions on how to flatten the folder structure without overwriting files with similar names?

My ultimate goal is to convert the unique names into sequential numbers as described in "Renaming files in a folder to sequential numbers"

  for i in *.jpg; do
  new=$(printf "%04d.jpg" "$a") #04 pad to length of 4
  mv -- "$i" "$new"
  let a=a+1

merged by Michael Mrozek Jan 7 '16 at 20:38

This question was merged with Flattening complex folder structures with duplicate file names because it is an exact duplicate of that question.

  • 1
    What hidden files are these? None of the answers of the suggested duplicate should create hidden files. Are you sure it isn't just finding hidden files that are already there? – terdon Jan 6 '16 at 23:53
  • OP reposted; merging this copy – Michael Mrozek Jan 7 '16 at 19:37