Skip to content

Instantly share code, notes, and snippets.

@barbolani
Created February 18, 2015 18:45
Show Gist options
  • Save barbolani/9168ebb54dbbb8402524 to your computer and use it in GitHub Desktop.
Save barbolani/9168ebb54dbbb8402524 to your computer and use it in GitHub Desktop.
Bash script to clean up file names
#!/bin/bash
#
# Often multimedia files downloaded from the internet contain
# as part of the filename things like the site from where they came
# the local language of the audio and such info that is not useful
# when you archive the file to your multimedia repository.
#
# This script renames a set of files, removing everything that does
# not look like part of the file name
#
# The idea is that a file named
#
# My Wedding [www.sharefiles.com]by-Pete-Spanish.avi
#
# is renamed to
#
# My Wedding.avi
#
until [ -z "$1" ]
do
INPUTFILE=$(basename "$1")
# Remove file extension assuming it is what is after the last dot in the filename
FILENAME=$(echo $INPUTFILE | sed 's/\.[^.]*$//')
# Keep the file extension to add it later
INPUTFILELENGHT=${#INPUTFILE}
FILENAMELENGTH=${#FILENAME}
FILEEXTENSION=${INPUTFILE:$FILENAMELENGTH:$INPUTFILELENGHT-$FILENAMELENGTH}
# Keep file in the same folder as it is now
OUTDIR=$(dirname "$1")
# Remove everything that appears after an open parenthesis or open bracket and replace dots with spaces
OUTFILENAME=$(echo $FILENAME | sed "s/\[.*$//g" | sed -r "s/\(.*$//g" | sed "s/\./ /g" | sed "s/ / /g")
OUTFILE=$OUTFILENAME$FILEEXTENSION
COMMAND='mv '\"$1\"' '\"$OUTDIR/$OUTFILE\"
eval $COMMAND
shift
done
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment