Posts tagged with “shell-scripting”

shellscripts: batch renaming

Monday, 26 February, 2007

Every time I sit down to write a shell-script, I have to stop and think. I seem to have a mental black hole in my head; into which all useful shell information inevitably seems to fall.

For example, I always forget whether a “do” or “loop” comes at the end of the for-loop line (answer: it’s “do”)

Therefore, from now on, I’m now going to note-down useful scripts as I write them, so next time I have a senile moment, I can look them up easily.

– snip –

The following script can be used to batch rename files — for example, I created a few hundred files with quotes in the name (don’t ask), so rather than recreate all the files, this script uses tr (translation) to remove quotes in the new filename:


for x in `ls *.xml*`
do
    export x2=`echo $x | tr -d ["]`
    mv $x $x2
done

(single line version):


for x in `ls *.xml*`; do export x2=`echo $x | tr -d ["]`; mv $x $x2; done

Note #1: it doesn’t take into account the fact that some files don’t have quotation marks, so those move statements cause an error (but doesn’t otherwise cause any problems).

Note #2: there’s probably a quicker and easier way to do this…