Shell Scripts

Below are a couple of UNIX shell scripts that can be useful.

Listing Big Files
This script uses the find command to find files bigger than a certain size and list them with their sizes. It doesn't matter if the files have spaces in them. Use it like sizefind.sh directory 100, where the number is in kilobytes.

#This script will find files in the given directory with more than the given kilobytes.
#It defaults to the current directory and 1000 kb.
#Default vaules
#Override with the arguments
if test -n "$1"; then mydir=$1; fi;
if test -n "$2"; then mysize=$2; fi;
#Say what we will do
echo Finding files in $mydir greater than $mysize kb
#Look for the files
files=`find ${mydir} -size +${mysize}k | sed -e "s/ /?/g"`
#List the files or say that no files were found
if test -n "$files"; then ls -l $files;
else echo "No files found"; fi;

Replacing Text
The following script can replace one string with another string in multiple files. It can use regular expressions. Always make a backup before running this script, as unexpected regular expressions can lead to losing files. Use it like replace.sh oldthing newthing *.php.

#Paul 29/4/2004
#This script replaces occurrences of one string with another in a bunch of files.
#Use like this: ./replace.sh NewCategory Category `find . -name \*php`
#the temporary file to use
#print a usage message
if test $# -lt 3; then
	echo Usage $0 replace_this with_this files
        exit 1
#get the replacement and text to replace
replacethis=$1 #the first argument
withthis=$2 #the second argument
shift 2
#loop through the files
for file; do
        nummatches=`grep "$replacethis" $file | wc -l | sed -e "s/ //g"`
        if test $nummatches -eq 0; then
                echo $file: 0 occurrences
                #We move first then sed, because doing it the other way around made the files give
                #permission denied when viewed as web pages (???)
                mv $file $TEMPFILE
                sed -e "s~$replacethis~$withthis~g" $TEMPFILE > $file
                if test -s $file; then
                        echo $file: replacing $nummatches occurrences
                        rm $TEMPFILE
                        echo $file: not changed as the expression made the file blank!
                        mv $TEMPFILE $file