Reputation: 636
I'm having problems with a find & replace batch script I've written. I need to be able to open a text file and change some values in it from the windows command line. I can't install sed.exe or FART or powershell so I need to do it this way. It was so much easier to do in linux....
So far I've written this following scrtipt which works perfectly if I'm using a file that only has one word per line, so I can easily change files in the following format
aaa
bbb
ccc
And here's the batch file:
@echo off
setlocal enabledelayedexpansion
if not exist "%1" (echo this file does not exist...)&goto :eof
for /f "tokens=* delims=" %%a in (%1) do (
set write=%%a
if "%%a"=="%2" set write=%3
echo !write!
(echo !write!)>>%~n1.replaced%~x1
)
del %1
rename %~n1.replaced%~x1 %1
My problem is that most of the files I need to change consist of lines of multiple values of strings and numbers, like this:
AAA 1.5
BBB 25
CCC 0.1
Can anyone tell me why my script won't change BBB 25 to BBB 45? Is it something to do with the delimiter being a space? I'm pretty sure it has nothing to do with numbers, as if i have a file of words just separated by spaces my script won't work either.
I've been searching through the forums and haven't spotted this problem yet but i'll keep searching. Anyway your help will be greatly appreciated.
UPDATE
Problem Solved!! I found this revision of BatchSubstitute.bat on DosTips.com and just adding an extra echo to a temporary file has solved my problem. I'm still not sure why the code I posted doesn't work so if anyone could explain that it would be great. I'm still quite new to all this!!
Update 2
Here's a typical input file that I need to change from:
k1 1e3
k2 2e5
n 1.5
x 10
And after I run the script (replace.bat prefs.txt "k1 1e3" "k1 5e4") it should be:
k1 5e4
k2 2e5
n 1.5
x 10
It should be able to change any line in the file. The version in the forum in the previous update seems to be able to work, I just have no idea why the first version I posted doesn't work.
Upvotes: 3
Views: 2117
Reputation: 15923
yes, the problem lies with spaces (or quote marks, if you try to keep the text together)
With a command line of test test.txt BBB 25 BBB 45
, then %2 is BBB
and it wont match the BBB 25
as the 25 is missing
With a command line of test test.txt "BBB 25" "BBB 45"
, then %2 is "BBB 25"
and it wont match the BBB 25
as the quotes are missing.
Upvotes: 0
Reputation: 82287
To answer your update2 question.
It should be able to change any line in the file. The version in the forum in the previous update seems to be able to work, I just have no idea why the first version I posted doesn't work.
It's because the line
if "%%a"=="%2" set write=%3
will not match any of your lines.
As %2
will be expanded to "k1 1e3"
so the line will expanded to
if "%%a"==""k1 1e3"" set write="k1 5e4"
A simple tilde should do the trick
if "%%a"=="%~2" set write=%~3
Upvotes: 1