I have running the following program,
@echo off
cls
set /p "filename=type file name>"
setlocal enabledelayedexpansion
for /r E:\ %%a in (*) do if "%%~nxa"=="%filename%" (
echo %%~dpnxa >>path.txt
)I have got a output file path.txt which contains,
E:\new.txt
E:\Redmi\new folder\new.txt
E:\windows\new folder\new folder\new.txtI like to have those in separate files like,
E:\new.txt in path1.txt
E:\Redmi\new folder\new.txt in path2.txt
E:\windows\new folder\new folder\new.txt in path3.txt
2 Answers
How can I separate single text file into multiple text file by lines?
Building on the comment by Seth, you can use the following batch file:
@echo off
cls
setlocal enabledelayedexpansion
set /p "filename=type file name>"
rem initialise counter to 1
set _count=1
for /r E:\ %%a in (*) do if "%%~nxa"=="%filename%" ( echo %%~dpnxa >>path!_count!.txt rem increment the counter set /a _count+=1 )
endlocalNotes:
- I have moved the
setlocalline in order to stop the variablefilenameleaking into the callingcmdshell.
Further Reading
- An A-Z Index of the Windows CMD command line
- A categorized list of Windows CMD commands
- enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
- endlocal - End localisation of environment changes in a batch file. Pass variables from one batch file to another.
- for /r - Loop through files (Recurse subfolders).
- set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
- setlocal - Set options to control the visibility of environment variables in a batch file.
I have a much simpler, and probably faster solution for you:
- Use
DIR /S /B /A-Dinstead ofFOR /Rto get the path list. This eliminates the need for anIFstatement. - Pipe to
FINDSTR /N, matching on the beginning of a line, to get the line number for use in output file name. - Execute the entire thing within
FOR /Fto iterate and parse the results into the line number and the path of each line.
@echo off
setlocal
set /p "filename=type file name>"
for /f "delims=: tokens=1*" %%A in ( 'dir /s /b /a-d "E:\%filename%" ^| findstr /n "^"'
) do >"path%%A.txt" echo %%BIf it were my script, I would pass the target filename as an argument rather than prompt for it:
@echo off
for /f "delims=: tokens=1*" %%A in ( 'dir /s /b /a-d "E:\%~1" ^| findstr /n "^"'
) do >"path%%A.txt" echo %%B