Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming files by folder hierarchy

I have many files with the following structure:

1969/ar/1.jpg
1969/ar/2.jpg

1969/he/1.jpg
1969/he/2.jpg

1969/en/1.jpg
1969/en/2.jpg

1970/ar/1.jpg

etc...

I want to rename all of them, with one command, to one directory, while their names reflect their original folder location.

1969_ar_1.jpg
1969_ar_2.jpg

1969_he_1.jpg
1969_he_2.jpg

1969_en_1.jpg
1969_en_2.jpg

1970_ar_1.jpg

etc...

Is it possible to do so with one command or a batch file?

Thanks!

like image 976
Hanan Cohen Avatar asked Dec 26 '22 01:12

Hanan Cohen


1 Answers

You may do that to move the files to the base folder with this command-line:

for /R %a in (*) do @set f=%a& set f=!f:%cd%\=!& move "%a" !f:\=_!

Execute it from the folder that contain the 1969, 1970... folders. IMPORTANT!: Delayed Expansion must be active in order for this line to work, so you must previously activate it executing cmd.exe with /V switch this way: cmd /V.

For example:

>xcopy test backup /s
test\1969\ar\1.jpg
test\1969\ar\2.jpg
test\1969\en\1.jpg
test\1969\en\2.jpg
test\1969\he\1.jpg
test\1969\he\2.jpg
test\1970\ar\1.jpg
7 File(s) copied

>cd test

>dir /B
1969
1970

>for /R %a in (*) do @set f=%a& set f=!f:%cd%\=!& move "%a" !f:\=_!

>dir /B
1969
1969_ar_1.jpg
1969_ar_2.jpg
1969_en_1.jpg
1969_en_2.jpg
1969_he_1.jpg
1969_he_2.jpg
1970
1970_ar_1.jpg

Modify the line this way to move the files to another folder:

for /R %a in (*) do @set f=%a& set f=!f:%cd%\=!& move "%a" "\other\folder\!f:\=_!"

Or via this Batch file:

@echo off
setlocal EnableDelayedExpansion
for /R %%a in (*) do set f=%%a& set f=!f:%cd%\=!& move "%%a" "\other\folder\!f:\=_!"
like image 87
Aacini Avatar answered Jan 02 '23 10:01

Aacini