Search & replace string in multiple files

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
^rooker
Site Admin
Posts: 1483
Joined: Fri Aug 29, 2003 8:39 pm

Search & replace string in multiple files

Post 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.
Jumping out of an airplane is not a basic instinct. Neither is breathing underwater. But put the two together and you're traveling through space!
Post Reply