从文本文件中获取字符串并使用文本文件中的字符串搜索并替换另一个字符串的最佳方法是什么?

时间:2010-08-10 02:10:58

标签: perl command-line vbscript

从文本文件中获取字符串并使用文本文件中的字符串搜索并替换另一个字符串最好的方法是什么?

E.g c:\output.txtabcdc:\newfile.txtStack overflow is great

我想将great替换为abcd

这样做的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以下载sed for windows然后

set /p var=<output.txt
sed "s/%var%/Stackoverflow is great/g" newfile.txt

答案 1 :(得分:1)

由于Perl是你的第一个标签,我猜你想要一个Perl版本的解决方案。

如果您在Windows上安装了Perl,则以下工作(为了便于阅读而添加了空格):

C:\>perl  -e "open(my $rf, '<', 'c:\output.txt') 
                 || die \"Can not open c:\output.txt: $!\"; 
              my $replace = <$rf>; 
              chomp $replace; 
              close $rf; 
              local $^I='.bak'; # Replace inside the file, make backup
              while (<>) {
                  s/great/$replace/g; 
                  print;
    }" c:\newfile.txt

C:\>type C:\newfile.txt
Stack overflow is abcd

要使用更多Windows惯用语,您可以使用“cmd”的SET /P命令(请参阅Ghostdog的asnwer)替换Perl代码的开头(读取文件内容),更短的Perl代码:

C:\> set /p r=<c:\output.txt
C:\> perl  -pi.bak -e "s/great/%r%/g;" c:\newfile.txt

C:\> type C:\newfile.txt
Stack overflow is abcd