#!/bin/bash# Shell script to find and remove files with a particular extension under a directory and its subdirectories (recursively). # Directory names are preceeded by a hash sign, files names are displayed in an absolute format.# Duy Dinh, IRIT - University of Toulouse, Febr. 2012args=$*# program arguments except $0inputDir="."# current directoryextensions=""# list of file extensionsfileFilterSpec=""# file filter specification (e.g., txt|html|php)useFilter=0# use file filtering (1) or not (0)recursive=0# recursive file listing
usage(){echo"Usage:"echo"sh removeFiles.sh [-r] [-d inputDir] -e filtersension"echo"Example:"echo"sh removeFiles.sh -r -d ./ -e \"htm|html|txt|php\""}# check whether file extension is valid or not
checkFileExtension(){localextension=$1matchExtension=0# returned value of this functionlocalext="";#echo "extensions: $extensions"for ext in $extensionsdo#echo $extif[$ext=$extension]||[$ext=".${extension}"]then#echo "Matched"matchExtension=1breakfidone}# function browse_directory
browse_directory(){if !(test -d "$1")thenecho"File or directory not found: $1";return;ficd"$1"path=`pwd`# directory name #echo "#$path"# get file entries from current pathfor e in *
doiftest -d "$e"# entry is a directorythenif[$recursive=1]then
browse_directory "$e"#list files recursivelycd ..
fielse# file entry# get file extension extension=${e##*.}
checkFileExtension $extension#echo $matchExtension# if not use file filtering, test file extension with or without the period beforeif[$useFilter=0]||[$matchExtension=1]then# make file name absolutepath=`pwd`;# directory name path="$path/$e";# file nameecho"Removing file $path"
rm "$path"fifidone}# main procedure
main(){if(test$# -eq 0)then
usage
exitfiinputDir=$1# parse optionswhilegetopts":d:e:o:rh" args;docase$args in
d)inputDir=$OPTARG;;
e)fileFilterSpec=$OPTARG# echo $fileFilterSpec# transform filters into list of extensions extensions=`echo$fileFilterSpec| tr ";,:|"" "`;;
r)recursive=1;;
h)
usage
exit;;
?)# unknown optionecho"Invalid option: -$OPTARG"
exit;;esacdone# file filter or notuseFilter=`expr length "$fileFilterSpec"`echo"Input directory: $inputDir"iftest$useFilter -gt 0thenecho"File filter(s) $fileFilterSpec"elseecho"Please specify file extension and try again!"exitfi# browse input directory
browse_directory $inputDir}# call main procedure
main $args
Last edit: Duy Dinh 2012-03-07
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Last edit: Duy Dinh 2012-03-07