Search code examples
linuxbashsh

Script to rename files in subfolders to different name


I have a directory with several folders inside. Inside the folders I have a worksheet with the same name in all folders. I need to run a script that randomly changes the name of the worksheets so that I can throw them all in the same folder. For example: worksheet1 worksheet2 worksheet3. today they are all called spreadsheet.csv I have a sketch in linux.

need help please.

NN=0; 
for arq in $(ls -1 *.csv);do
let NN++; 
rename -n 's/'${arq}'/spreadsheet'${NN}'.csv/' ${arq};
done 

(this search all files csv, but dont is recursive. Work only in one directory)


Solution

  • Use globstar:

    n=0
    shopt -s globstar nullglob || exit
    
    for f in **/*.csv; do
        until dst=spreadsheet$(( ++n )).csv; [[ ! -e ${dst} ]]; do
            continue
        done
    
        mv -i -- "${f}" "${dst}"
    done