Renaming multiple subdirectories with the name of parent directory as prefix

52 Views Asked by At

I have multiple directories 1111, 2222, 3333, 4444 and inside each directory is subdirectory named as for example _apple. I want to add the parent folder name as prefix to the sub directory.

What I have is

1111
 _apple

2222
 _apple

3333
 _apple

what I want is

1111
 1111_apple

2222
 2222_apple

3333
 3333_apple

Please if anyone can help ?

I tried this but it works for only 1st file and does not iterate. I have more than 100 directories and it works only for 1st one.

for folder in */; do 
    
    for sample_num in */; do
        cd $sample_num
        sample="${sample_num::-1}"
        for rename in _apple; do
            mv -- "$rename" "{$sample}_{$rename}"
        done
        cd ..
        cd ..
    done
2

There are 2 best solutions below

2
Barmar On

You don't need all the cd commands. Use a wildcard in both the directory and subdirectory portion. Then split it with parameter expansion operators to get the parent and child names.

for subdir in */*; do
    if [ -d "$subdir" ]
    then
        dirname=${subdir%/*}
        subdirname=${subdir#*/}
        mv "$subdir" "$dirname/$dirname$subdirname"
    fi
done
0
911 On

Saw you added the python tag to your question. Here is a workaround for python

from pathlib import Path

root = "The/directory/where/1111,2222,3333/are/located"
for i in Path(root).iterdir():
    for j in i.glob("*_apple"):
        j.rename(i / f"{i.name}{j.name}")