0

I have a large number of files in sub-folders that I need to rename. For example, I have:

ParentFolder/sub-Folders/*.jpg

How can I copy the files with a new naming convention as follows?

ParentFolder1.jpg
ParentFolder2.jpg
saladi
  • 3,103
  • 6
  • 36
  • 61
phh
  • 149
  • 1
  • 2
  • 10

2 Answers2

4

One way to do this is via GNU parallel. Tutorial here:

find ./ParentFolder -name "*.jpg" | parallel "mv {} DESTINATION/ParentFolder{#}.jpg"

To view the commands to be run before executing them, try:

find ./ParentFolder -name "*.jpg" | parallel --dryrun "mv {} DESTINATION/ParentFolder{#}.jpg"
saladi
  • 3,103
  • 6
  • 36
  • 61
1

Use rename over the full path using file globbing :

*/*

If you don't understand, you can test it with :

echo */*

First * is your directory, second * is your file name. Catch them in a regular expression :

(.*)/(.*)

Now $1 is your parent folder name and $2 is your file name. You can easily build your solution like this :

rename -n "s/(.*)\/(.*)/\$1\/\$1\$2/" */*

It keeps directory structure and adds directory name as a prefix to each of its files. You could move your files up by simply changing \$1\/\$1\$2 to \$1\$2. You then just have to delete empty directories using rmdir.

I voluntarily added the option -n so you don't do a mess if you copy-paste. Simply remove the option when you think it's good.

    adrien@adrienLT:~/Documents/PEV$ cp -r Holiday/ Holiday_copy/
adrien@adrienLT:~/Documents/PEV$ tree Holiday*
Holiday
├── France
│   ├── 1.jpg
│   ├── 2.jpg
│   └── 3.jpg
├── Italy1
│   ├── 1.jpg
│   ├── 2.jpg
│   └── 3.jpg
└── Italy2
    ├── 1.jpg
    ├── 2.jpg
    └── 3.jpg
Holiday_copy
├── France
│   ├── 1.jpg
│   ├── 2.jpg
│   └── 3.jpg
├── Italy1
│   ├── 1.jpg
│   ├── 2.jpg
│   └── 3.jpg
└── Italy2
    ├── 1.jpg
    ├── 2.jpg
    └── 3.jpg

6 directories, 18 files
adrien@adrienLT:~/Documents/PEV$ cd Holiday_copy/
adrien@adrienLT:~/Documents/PEV/Holiday_copy$ rename "s/(.*)\/(.*)/\$1\/\$1\$2/" */*
adrien@adrienLT:~/Documents/PEV/Holiday_copy$ tree .
.
├── France
│   ├── France1.jpg
│   ├── France2.jpg
│   └── France3.jpg
├── Italy1
│   ├── Italy11.jpg
│   ├── Italy12.jpg
│   └── Italy13.jpg
└── Italy2
    ├── Italy21.jpg
    ├── Italy22.jpg
    └── Italy23.jpg

3 directories, 9 files
Adrien Horgnies
  • 691
  • 4
  • 11