3

我有数百个文件需要更改其部分文本。

例如,我想用 "rtmp://" 替换 "http://" 的每个实例。

这些文件具有 .txt 扩展名,并分布在多个文件夹和子文件夹中。

我基本上是在寻找一种方式/脚本,它可以通过每个文件夹/子文件夹和每个文件,如果它在该文件中找到“http”的出现以用“rtmp”替换它。

4

2 回答 2

11

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
于 2012-11-13T16:27:00.123 回答
2

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)

于 2012-11-13T16:27:37.870 回答