Ubuntu – Rename files adding their parent folder name

command linescriptssoftware-recommendation

I want to rename file name with its parent folder name, adding the folder name before the current name.

for example:

Folder structure

SOCH NC KT 633-ROYAL BLUE-MULTI
|
| 1.jpg
|
| 2.jpg
|
| 3.jpg

Expected Result

SOCH NC KT 633-ROYAL BLUE-MULTI
|
|_SOCH NC KT 633-ROYAL BLUE-MULTI1.jpg
|
|_SOCH NC KT 633-ROYAL BLUE-MULTI2.jpg
|
|_SOCH NC KT 633-ROYAL BLUE-MULTI3.jpg

SOCH NC KT 710-BLACK-MULTI

Could anyone advise how this can be done in a .sh file? Is there any utility is available to do the operation?

Best Answer

In a small python script, renaming files recursively (folders as well as sub folders):

#!/usr/bin/env python3
import shutil
import os
import sys

dr = sys.argv[1]

for root, dirs, files in os.walk(dr):
    for f in files:
        shutil.move(root+"/"+f, root+"/"+root.split("/")[-1]+f)

How to use

  • Copy the script into an empty file, save it as rename_files.py
  • Run it with the directory as an argument:

    python3 /path/to/rename_files.py /directory/with/files
    

Note

As always, first try on a sample!

Explanation

The script:

  • Walks through the directories, looking for files.
  • If files are found, it splits the path to the file with the delimiter "/", keeping the last in the row (which is the parent's folder name) , to be pasted before the file's name:

    root.split("/")[-1]
    
  • Subsequently, move the file to the renamed one:

    shutil.move(root+"/"+f, root+"/"+root.split("/")[-1]+f)
    
Related Question