Nordanfors
Nordanfors

Reputation: 401

Bash script issue with renaming files from folder name

I have a bash script that does not produce the result I expected. It is intended to rename files in a folder structure in such a way that the files are sortable outside the folder structure.

The file structure is ripped from a typical audio book containing 10-20 CD discs. Uppermost folder is a Title folder that holds a folder for each disc, 01, 02, 03 etc.

Like this:

TITLE / 01 / File 01.wav,File 02.wav etc.
        02 / File 01.wav,File 02.wav etc.
        03 / File 01.wav,File 02.wav etc.
        etc...

The Script to rename the files using the folder names looks like this:

cd "$@"


pwd

IFS=$'\n'; for f in $(find "$PWD" -name '*.wav'); do folder=${f%/*}; file=${f##*/}; echo ${folder##*/}"/"$file "-->" ${folder##*/}$(printf %03d "${file%% *}") ${file#* } >> rename_log.out;  mv "$f" "$folder/${folder##*/}$(printf %03d "${file%% *}") ${file#* }";done

The issue is that something strange happens when it renames file 08 and 09. I can not figure out why it happens.

Here is the output log file from a run (rename_log.out):

01/01 - Track 01.wav --> 01001 - Track 01.wav
01/02 - Track 02.wav --> 01002 - Track 02.wav
01/03 - Track 03.wav --> 01003 - Track 03.wav
01/04 - Track 04.wav --> 01004 - Track 04.wav
01/05 - Track 05.wav --> 01005 - Track 05.wav
01/06 - Track 06.wav --> 01006 - Track 06.wav
01/07 - Track 07.wav --> 01007 - Track 07.wav
01/08 - Track 08.wav --> 01000 - Track 08.wav
01/09 - Track 09.wav --> 01000 - Track 09.wav
01/10 - Track 10.wav --> 01010 - Track 10.wav
01/11 - Track 11.wav --> 01011 - Track 11.wav
01/12 - Track 12.wav --> 01012 - Track 12.wav
01/13 - Track 13.wav --> 01013 - Track 13.wav
01/14 - Track 14.wav --> 01014 - Track 14.wav
01/15 - Track 15.wav --> 01015 - Track 15.wav
01/16 - Track 16.wav --> 01016 - Track 16.wav

Notice track 8 & 9 and how they are renamed. I would expect them to be 01008 & 01009 but they are not. What am I missing???

Any help here is much appreciated.

//Johan

Upvotes: 1

Views: 342

Answers (1)

Jim Black
Jim Black

Reputation: 1482

Reformatted and repaired.

cd "$@"
pwd
IFS=$'\n'
for f in $(find "$PWD" -name '*.wav'); do
  folder=${f%/*}
  file=${f##*/}
  echo ${folder##*/}"/"$file "-->" ${folder##*/}$(printf %03d "$(( 10#${file%% *} ))") ${file#* } >> rename_log.out
  mv "$f" "$folder/${folder##*/}$(printf %03d "$(( 10#${file%% *} ))") ${file#* }"
done

Notice the octal to decimal conversion added to the variable being passed to printf.

Upvotes: 2

Related Questions