Blender Fox


Bash Snippet: basename

#

I love linux and bash scripting. Whilst I am no expert, I really love the way you can pipe one application’s output into another.

One thing I don’t like to much about linux, however, is the case-sensitivity. “file.ext” is not the same as “file.EXT”, for example. On Windows, it doesn’t much care about the case of the extension, but on linux, it does. And therein is my problem.

My digital camera takes pictures and gives them a .JPG extension, which doesn’t show up on listings on my linux box where the application is looking for .jpg extensions. Sure, I can rename them manually, or macro together a simple bash script, but when you have to do this repeatedly, it gets quite frustrating.

So I did some research, and found out about the basename application. It serves two purposes. It strips out directory information to leave just the file name so that “dir1/dir2/dir3/file” becomes just “file” and optionally, allows you to strip out a suffix from the name, so for example to rename all .JPG files to .jpg in the current folder, I would use this:

for a in *.JPG
 do
   mv $a `basename $a .JPG`.jpg
 done

Here’s an example output

$ ls
file1.JPG file2.JPG file3.JPG

$ for a in *.JPG
> do
> echo mv $a `basename $a .JPG`.jpg
> done
mv file1.JPG file1.jpg
mv file2.JPG file2.jpg
mv file3.JPG file3.jpg

$ for a in *.JPG
> do
> mv $a `basename $a .JPG`.jpg
> done

$ ls
file1.jpg file2.jpg file3.jpg