Pattern-based file renaming
Ever wanted to do bulk operations on files, similar to xargs, but much more flexible? For example:
- rename all files .jpeg to .jpg
- remove a prefix from many file names?
- add a suffix/extension?
- remove a prefix/suffx/extension?
Here’s a script I wrote:
!/bin/bash
#
Pattern-based file rename
#(c)2006 by Tadeusz Pietraszek
#
Usage:
./mv-pattern -i a *.txt <- delete all 'a's in file names
./mv-pattern -i jpeg -o jpg *.jpeg <- rename all jpegs to jpg
./mv-pattern -o .txt <- add an extension
./mv-pattern -i .txt <- remove an extension
#
if [ $# -eq 0 ]
then
echo "Usage: basename $0 [-i
INPATTERN=""; OUTPATTERN=""; COMMAND="echo";
while getopts "i:o:c:" Option do case $Option in i ) INPATTERN=$OPTARG;; o ) OUTPATTERN=$OPTARG;; c ) COMMAND=$OPTARG;; * ) echo "Unimplemented option chosen. Has to be one of -i -o -c"; exit -1;; esac done
if [ -z "$INPATTERN" ]; then echo "No input pattern. Are you sure it's what you want?";
exit -1;
fi
if [ -z "$INPATTERN" ]; then echo "No input pattern. Are you sure it's what you want?";
exit -1;
fi
shift $(($OPTIND - 1))
Decrements the argument pointer so it points to next argument.
echo "in: $INPATTERN, out: $OUTPATTERN";
rename
for FILE in "$@" ; do
if [ -f $FILE ]; then
NEWFILE=echo $FILE | sed -re "s/(.*)$INPATTERN(.*)/\1$OUTPATTERN\2/";
if [ "$FILE" != "$NEWFILE" ]; then
$COMMAND $FILE $NEWFILE;
fi;
fi;
done
exit 0
April 10th, 2006 at 6:32 pm
From a note from James: A simple pattern-based file renaming can be done using simple bash parameter expansion, for example, using the following command:
Another thing to look at might be
${parameter/pattern/string}Thanks!
August 22nd, 2006 at 10:00 am
There is a perl utility called “rename” which does what you describe with regular expressions. eg:
strips the extension “.bak” from all files the glob returns.