Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch replace text inside text file (Linux/OSX Commandline)

I have hundreds of files where I need to change a portion of its text.

For example, I want to replace every instance of "http://" with "rtmp://" .

The files have the .txt extention and are spread across several folders and subfolder.

I basically am looking for a way/script that goes trough every single folder/subfolder and every single file and if it finds inside that file the occurrence of "http" to replace it with "rtmp".

like image 695
user1596553 Avatar asked Oct 30 '25 20:10

user1596553


2 Answers

You can do this with a combination of find and sed:

find . -type f -name \*.txt -exec sed -i.bak 's|http://|rtmp://|g' {} +

This will create backups of each file. I suggest you check a few to make sure it did what you want, then you can delete them using

find . -name \*.bak -delete
like image 131
Kevin Avatar answered Nov 03 '25 06:11

Kevin


Here's a zsh function I use to do this:

change () {
        from=$1 
        shift
        to=$1 
        shift
        for file in $*
        do
                perl -i.bak -p -e "s{$from}{$to}g;" $file
                echo "Changing $from to $to in $file"
        done
}

It makes use of the nice Perl mechanism to create a backup file and modify the nominated file. You can use the above to iterate through files thus:

zsh$ change http:// rtmp:// **/*.html

or just put it in a trivial #!/bin/zsh script (I just use zsh for the powerful globbing)

like image 27
Brian Agnew Avatar answered Nov 03 '25 06:11

Brian Agnew