Quick and Easy Regular Expression Command/Script to Run on Files in the Bash Shell

I often find it necessary to run regular expressions on, not just one file; but instead a range of files. There are perhaps dozens of ways this can be done, with varying levels of understanding necessary to do this.

The simplest way I have encountered utilizes the following syntax:

perl -pi -e "s///g" 

Here is an example where I replace the IP address in a range of report templates with a different IP address:

perl -pi -e "s/mysql:\/\/\/\/" $reportTemplateLocation/*.rpt*

Basically, I am looking for a line which contains mysql://, which I want to replace with mysql://

Here is an example of a bash script I call changeReportTemplateDatabase.sh, which I wrap around that command, to accomplish that same task with more elegance:

# @(#)$Id$
# Point the report templates to a different database IP address.

    echo "$arg0: $*" 1>&2
    exit 1
        echo "Usage $0 -o  -n ";

while getopts hvVo:n: flag
    case "$flag" in
    (h) help; exit 0;;
    (V) echo "$arg0: version 0.1 8/28/2010"; exit 0;;
    (v) vflag=1;;
    (o) oldip="$OPTARG";;
    (n) newip="$OPTARG";;
    (*) usage;;
shift $(expr $OPTIND - 1)

if [ "$oldip" = "" ]; then
        exit 1;
if [ "$newip" = "" ]; then
        exit 1;

echo "$0: Changing report templates to use the database at $newip from $oldip";
perl -pi -e "s/mysql:\/\/$oldip/mysql:\/\/$newip/g" $reportTemplateLocation/*.rpt*

Usage of the script is as simple as the command below. It will change every database reference on report templates in the directory referenced by the variable reportTemplateLocation to the new value.

./changeReportTemplateDatabase.sh  -o -n

A further improvement, which may be useful to some, would be to make the directory a flag which can be edited at the command line.

One response to “Quick and Easy Regular Expression Command/Script to Run on Files in the Bash Shell”

Leave a Reply

Your email address will not be published. Required fields are marked *