windows batch splitting file in to two based on conditions

假装没事ソ 提交于 2021-02-11 17:48:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!