Removing numbers and hyphens from file names recursively
I am modifying a simple BASH script to remove numbers and hyphens from the start of my MP3 files. The aim is to rename files such as:
- 11 Song 1.mp3
- 1-1-Song 2.mp3
- 11-1 Song 3.mp3
to:
- Song 1.mp3
- Song 2.mp3
- Song 3.mp3
I have this script which works for all the files in the current directory
$ for f in [0-9]*; do mv "$f" "`echo $f | sed 's/^[0-9]*\W*//'`"; done
and have modified it to look for all files inside subfolders:
#!/bin/bash
dir=''
IFS='
'
for f in $(find $dir * -type f) ; do
mv "$f" "`echo $f | sed 's/^[0-9]*\W*//'`";
done
The problem is that the $f
value returns the subfolder and the filename and the mv
line looks for files beginning with [0-9], therefore any files within a subfolder are not being renamed.
E.g. The file mp3/1-1 Song 1.mp3
begins mp3/
, does not start with a numeric so it's not renamed.
Is there a way I can read the directory and file values into separate variables or is there a better way of doing this?
Thanks
Solution 1:
find & sed: I would ask you to first remove the pipe and sh at the end, and see whether the mv command is getting generated properly, and then you can run the command as such:
find $dir -type f | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh
Solution 2:
Theres no need for a script, there's a one liner for that.
Try this to see what it does (don't worry, this doesn't rename your files yet, see below):
find root_audio_path -type f -iname '*mp3' -execdir rename --no-act 's/^\.\/[\d\s\-]+/\.\//' '{}' ';'
Remove --no-act
if it seems to work. This actually renames the files.
The -execdir
option of find
makes sure that rename
is executed in the files directory, so the files paths always start with ./
- for which we look for in rename
.
rename
in Ubuntu actually perls rename, so you can use regular expressions there.