views:

62

answers:

2

What would the best way be to take a string from a text file and search and replace another string with the one from the text file?

E.g c:\output.txt has abcd and c:\newfile.txt has Stack overflow is great.

I would like to replace great with abcd.

What would be the best approach to do this?

+1  A: 

you can download sed for windows and then

set /p var=<output.txt
sed "s/%var%/Stackoverflow is great/g" newfile.txt
ghostdog74
+1: After years of BATting, I'd seen "set /p" before
Adrian Pronk
+1  A: 

Since Perl was your first tag, I guess you'd want a Perl version of the solution.

If you have Perl installed on your Windows, the following works (whitespace added for readability):

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

To be a bit more Windows idiomatic, you can replace the start of the Perl code (reading of the contents of a file) with a "cmd"'s SET /P command (see Ghostdog's asnwer), for a much shorter Perl code:

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
DVK
I used DVK's solution. It worked great. Thank You!
moorecats
@moorecats - welcome. If it was useful, feel free to up-vote (up arrow next to the answer) and accept (the checkmark next to the answer) my answer.
DVK