问题
I have a file where the starting words are any case "add" "changeprop" OR "anyother" I am trying to read such file and based on if conditions pushing that specific line to add.txt , changeprop.txt and errorrecords.txt
Having hard time at the substing place as the variable is not holding the line value and i am unable to finish this job :(
set "File=.\WorkFlow_Action_Script_Merged_Folder\All_WorkFlows_Merged_File.txt"
SETLOCAL enabledelayedexpansion
for /F "tokens=* delims=" %%a in ('Type "%File%"') do (
SET eachline=%%a
IF "%eachline:~0,3%"=="ADD" ( echo "%eachline%">>.\WorkFlow_Action_Script_Merged_Folder\ADD_WorkFlows_Merged_File.txt)
IF "%eachline:~0,3%"=="and" ( echo "%eachline%">>.\WorkFlow_Action_Script_Merged_Folder\ADD_WorkFlows_Merged_File.txt)
IF "%eachline:~0,10%"=="CHANGEPROP" ( echo "%eachline%">>.\WorkFlow_Action_Script_Merged_Folder\CHANGEPROP_WorkFlows_Merged_File.txt)
IF "%eachline:~0,10%"=="changeprop" ( echo "%eachline%">>.\WorkFlow_Action_Script_Merged_Folder\CHANGEPROP_WorkFlows_Merged_File.txt)
REM pause
)
I feel like losing the mind - after trying call / internal block / differnt ways of using a variable . nothing is holding value of the just read line for substring compare place. Please suggest.
回答1:
As you are using multiple if statements with one command each, you do not need to parenthesize the echo
commands. Your problem however is actually the fact that you enabledelayedexpansion
without actually using it. You can also simply use /i
switch with the if
statement to be case insensitive, so no need to check each line twice for a match. Lastly, I would use %~dp0
instead of .\
@echo off
setlocal enabledelayedexpansion
set "File=%~dp0WorkFlow_Action_Script_Merged_Folder\All_WorkFlows_Merged_File.txt"
for /F "tokens=* delims=" %%a in ('Type "%File%"') do (
set "eachline=%%a"
if /i "!eachline:~0,3!" == "ADD" echo "!eachline!">>"%~dp0WorkFlow_Action_Script_Merged_Folder\ADD_WorkFlows_Merged_File.txt"
if /i "!eachline:~0,10!" == "CHANGEPROP" echo "!eachline!">>"%~dp0WorkFlow_Action_Script_Merged_Folder\CHANGEPROP_WorkFlows_Merged_File.txt"
)
回答2:
The following code does the same, is less error-prone and probably a lot faster:
@echo off
set "File=.\WorkFlow_Action_Script_Merged_Folder\All_WorkFlows_Merged_File.txt"
Type "%File%" |findstr /bi "add" > .\WorkFlow_Action_Script_Merged_Folder\ADD_WorkFlows_Merged_File.txt
Type "%File%" |findstr /bi "changeprop" >.\WorkFlow_Action_Script_Merged_Folder\CHANGEPROP_WorkFlows_Merged_File.txt
来源:https://stackoverflow.com/questions/60201808/windows-batch-splitting-file-in-to-two-based-on-conditions