Page 1 of 1

Search & replace string in multiple files

Posted: Fri Dec 15, 2006 1:00 pm
by ^rooker
I had to replace IPs within several m3u files by a hostname.

Thanks to the info on this site, I had the one-liner that does the trick:

Code: Select all

find . -name '*.txt' |xargs perl -pi -e 's/find/replace/g'
I've used this regexp for matching any IP:

Code: Select all

\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
I've slightly enhanced it a bit for being reusable by others on our machine, too:

Code: Select all

#!/bin/bash
#
# replaces a certain pattern in multiple files.
# @author:      ^Rooker
# @date:        Dec 15th, 2006

FILEMASK="*.m3u";
HOSTNAME="www.das-werkstatt.com";

case "$1" in
        GO)
                find . -name "$FILEMASK" | xargs perl -pi -e "s/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/$HOSTNAME/g"
        ;;

        LIST)
                find . -name "$FILEMASK"
        ;;

        *)
                echo;
                echo "Replaces any IP within $FILEMASK files by a given hostname ($HOSTNAME)"
                echo "SYNTAX: $0 (GO|LIST)";
                echo;
        ;;
esac
NOTE: I had to replace the single-quotes by double quotes to use bash variables.