Posts Tagged ‘rename’

Rename files with number using bash

Tuesday, July 12th, 2011

I had a bunch of jpegs:


 my_file_name.jpg
 my_other_file_name.jpg
 here's_one.more.jpeg
 ...
 my_fiftieth_file.jpg

and I want to quickly rename them to


01.jpg
02.jpg
03.jpg
...
50.jpg

I do this with the following small script in bash. Save this in rename_numbered.sh:

#!/bin/bash
# USAGE: rename_numbered.sh files
x=1;
pad=`echo "(l($#+1)/l(10)) + 0.5" | bc -l`
for var in "$@"
do
  dn=`dirname $var`;
  ext=${var##*.}
  echo $ext
  echo "mv \"$var\" \"$dn/`printf '%0'$pad'd' $x`.$ext\""
#uncomment next line to enable
#  mv "$var" "$dn/`printf '%0'$pad'd' $x`.$ext"
  x=$(($x+1));
done

Then you can rename a bunch of files, like all those in a directory with:


./rename_numbered.sh path/to/dir/*

Replace string in file names, bash one-liner

Saturday, December 5th, 2009

After running lame on a bunch of wav files I ended up with tons of files named:


song1.wav.mp3
song2.wav.mp3
song3.wav.mp3
song4.wav.mp3
...

Now, obviously I could have avoided this in this case with the proper options and arguments to lame, but it’s all in hindsight.

Here’s the bash line I use to strip out .wav from the middle of all these files in the current directory:


for filename in *.mp3; do newname=`echo $filename | sed 's/\.wav\.mp3$/.mp3/g'`; mv $filename $newname; done

It’s long for one line but I think it’s still understandable and manageable. The result is:


song1.mp3
song2.mp3
song3.mp3
song4.mp3
...

Note: I notice that I’m being overly carefully with my regexes and wildcards in the example above but it should make it more clear how to adapt it to your case.