Home > OS >  How to copy all files having the same name into another directory, with unique filenames, using bash
How to copy all files having the same name into another directory, with unique filenames, using bash

Time:10-17

Say I have a directory structure like this:

├── Directory 1
│   ├── img.png
├── Directory 2
│   ├── imgx.png
├── Directory 3
│   ├── img.png
...
...
├── Directory n
│   ├── img.png
├── Images

I want to find and copy all the img.png files into the directory Images. Is there any way to:

  1. Find all the img.png files (not all directories have this file)
  2. Copy them into Images giving them unique filenames in the process (for example 2_img.png if it is being copied from Directory 2).

CodePudding user response:

You're looking for something like this:

for dir in 'Directory '*; do
  src=$dir/img.png
  dest=Images/${dir#* }_img.png
  if test -f "$src"; then
    echo cp "$src" "$dest"
  fi
done

Remove echo if the output looks good.

  •  Tags:  
  • bash
  • Related