tero.co.uk

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.

#!/bin/sh
#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
mydir="."
mysize=1000
 
#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.

#!/bin/bash
#This script replaces occurrences of one string with another in a bunch of files.
#Use like this: ./replace.sh oldthing newthing `find . -name \*php`
#the temporary file to use
TEMPFILE=/tmp/replaceZZ.tmp
#print a usage message
if test $# -lt 3; then
        echo Usage $0 replace_this with_this files
        exit 1
fi
#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
        else
                echo $file: replacing $nummatches occurrences
                sed -e "s+$replacethis+$withthis+g" $file > $TEMPFILE
                mv $TEMPFILE $file
        fi
done