问题
I would like to search using a variable in one file, then take that variable result and replace part of some text in another file.
For exmaple in "1.txt" I have a text line of: ClassName=X
X changes within the file depending on the line of text that you search ClassName= So I would have to search using a variable with ClassName=
I would then search for X in another file after the word "Class=", replacing it with the word "ShipDummy". We'll call the second file "2.txt". X within the second file would be found like this: Class=X. However, I would like it to be Class=ShipDummy
I would search similar to the layout in 1.txt, but without the "Name" part, and 1.txt wont get ShipDummy either.
I would also like to make a backup of 2.txt before the replacement takes place.
Also, there are many ClassName= lines in 1.txt, all with different x values. I'd like it to give a variable for each x value, then doing the replace for that value in 2.txt. For example: ClassName=x in 1.txt (replace Class=x in 2.txt with Class=ShipDummy)
ClassName=y in 1.txt (replace Class=y in 2.txt with Class=ShipDummy)
ClassName=z in 1.txt (replace Class=z in 2.txt with Class=ShipDummy)
and so on....
Keep in mind, in the above I am using x, y and z as variables here.
How would I do all this? I am new to coding and its quite complex. I'd like this in a batch file.
What I have is something like this, but I'm lost:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /f "tokens=*" %%a in (1.txt) do
SETLOCAL ENABLEDELAYEDEXPANSION
for /f "delims=" %%A in ("!var2!") do echo !var1:Name=%%A!
exit
回答1:
Probably the easiest way to solve this is to approach it from the reverse direction.
Read each line in in 2.txt. If the line matches the templpate Class=X, then parse out X and search to see if ClassName=X exists in 1.txt. If it does exist, then write the replacement line, else write the original line.
You can search for a string within a file using FINDSTR. You don't care about the output, so output is redirected to null. The && operator conditionally executes code if the prior command (FINDSTR) was successful (matched).
@echo off
setlocal enableDelayedExpansion
>2.txt.new (
for /f "delims=" %%A in (2.txt) do (
set "ln=%%A"
if "!ln:~0,6!" == "Class=" findstr /c:"ClassName=!ln:~6!" 1.txt >null && set "ln=Class=ShipDummy"
echo !ln!
)
)
move 2.txt.new 2.txt
The script above is untested, but the concept should work. There is lots of room for improvement.
来源:https://stackoverflow.com/questions/14992029/batch-i-would-like-to-search-with-a-variable-in-one-file-and-replace-that-vari