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

时光毁灭记忆、已成空白 提交于 2019-12-03 03:55:14

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

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!