Showing posts with label BASH. Show all posts
Showing posts with label BASH. Show all posts

Thursday, July 9, 2009

Rename a bunch of files with a finger tip!

Some cameras have functions to set the name of photos taken, some don't. Some softwares, e.g.Digikam, offer the function to rename the files during import images from camera to a PC.
What about if your camera does not have the function to set the name of the photos or you, for whatever reason, want to rename your collection of files later?

Let's write a simple Bash script to do this job!

First, let us check if the parameters required are less than 3. I always add the usage and help here because this becomes handy whenever you want to know the script syntax.

$# is the argument count.
${0##*/} is the base name of $0 which is the script name to make the output short.
$1,$2 are the first and second arguments.

Next, let us make this change directly inside the directory.

for f in *.[jJ][pP][gG] means for each file matches .jpg or .JPG or .jPg or similar.
old_name=${f##*/} is to get the basename of the file.
new_name=${old_name//$old_string/$new_string} is to replace old string or search string with new string where the old string found in old_name or original file name, then give back the result to the new name.

That's it! A piece of cake, isn't it?





#!/bin/bash

if [[ $# -ne 3 ]]; then
echo "To rename jpg files in directory"
echo "usage: ${0##*/} new_string old_string directory"
echo "example: ${0##*/} Graz _MG ~/Pictures/Graz/web"
exit 1
fi

old_string=$2
new_string=$1

cd $3

for f in *.[jJ][pP][gG]
do
old_name=${f##*/} #base filename
new_name=${old_name//$old_string/$new_string} #replace string
if [ ! -w $f ]; then
echo "warning ...$f is not writable "
else
mv $f $new_name
echo "renaming ... $old_name -> $new_name"
fi
done
################END OF FILE##################

Tuesday, February 24, 2009

BASH 4.0 is out.

It has been announced on slashdot today. Visit:
- BASH main page
- What's new can be found here.

Other useful links for BASH user (from my bookmark):
- Advanced Bash-Scripting Guide from Mendel Cooper. The tutorial covers the detail from ground up. In the appendix, the author also introduced the "sed" and "awk" usages.
- BASH String Manipulations on Linuxgazette. It focuses on string handling with BASH.
- Bash Shell and Beyond (Stack and Queue, Array, Sort, XML parser expat).


---------------
"Part of the inhumanity of the computer is that, once it is competently programmed and working smoothly, it is completely honest." Isaac Asimov