command line - Rename files in different directories with the same name, so each has a unique (numbered) name - Ask Ubuntu


i need rename files on sd card, able copy contents of multiple sub folders hdd. first need find them extension .mod (i can using find ./path/*.mod2, in different directories).

i need rename them because have names mov001.mod, mov002.mod, in other directory other videos, named. created camera. after renaming, copy them 1 command hdd.

because of actual names, when use cp ./path/*.mod new-path, result overwrite named files.

how can solve this?

this tiny script renames files without moving them

n=0; files in dir1/*.mod dir2/*.mod dir3/*.mod; printf -v new "${files/mov*./%02d.}" "$((++n))"; echo mv -v "$files" "$new"; done 

or more readably:

#!/bin/bash n=0 files in dir1/*.mod dir2/*.mod dir3/*.mod;    printf -v new "${files/mov*./%02d.}" "$((++n))"    echo mv -v -- "$files" "$new" done 

replace dir1 etc actual paths directories files

remove echo (it's test) after checking gives want, rename files.

this numbers files 01.mod, 02.mod, etc. if have more 99 files, replace %02d %03d 001.mod etc


explanation:

n=0 sets n 0 want bash start counting from.

for files in dir1/*.mod dir2/*.mod dir3/*.mod 

a for loop can execute commands iteratively on each file in turn. syntax for [variable] in [these things want to] ; [command(s)] $[variable]; done have called variable files , found files using glob: *.mod expanded shell file name ends in .mod (* matches characters)

printf -v new 

printf can format new numbers fixed width easier sorting. new variable - new name files.

"${files/mov*./%02d.}" "$((++n))" 

referencing variable files earlier , replacing mov* (remember * character) result of incrementing number $((++n)) (this n first line of script, go 1 each time loop executed on file) formatted using code %02d printf means decimal number of fixed width of 2 digits 01, 02 etc. search , replace pattern includes . stop * matching whole filename , removing extension.

echo mv -v -- "$files" "$new" 

i add echo testing - shows done instead of doing it. remove echo when happy result execute command.

mv renames or moves files; syntax mv oldname newname. added -v flag tells mv "verbose" , report each action. added -- safe - tells mv not accept further options, stops filenames starting - being interpreted options command - not needed in case, practice.

each file specified files variable mved unique name created in new variable. use $ reference variables , these should in "double quotes" prevent shell doing other expansions on filenames - stops special characters or spaces in filenames causing problems.


Comments

Popular posts from this blog

download - Firefox cannot save files (most of the time), how to solve? - Super User

windows - "-2146893807 NTE_NOT_FOUND" when repair certificate store - Super User